forEach() and map()
forEach and map are behave like for loops but with one thing better than for loops. They are easier to read and they are understandable to someone who is just getting into javascript coding.
Lets take a look at forEach first. forEach pulls from an array, just as map does and can be written several ways, too bad I wasn’t taught the short way ;-;.
Ex. of for loop
for(var i = 0; i<arr.length; i++){
(code goes here)
}
ex. of forEach
example.forEach(function(demoExample){
(code goes here)
});
as you can see, forEach is much easier to read in terms of how it’s read along with how it looks. forEach is easier to look at when compared to for loops. Yes for loops may be shorter but forEach is easier to understand.
Now lets take a look at maps. Maps preform the same basic function just as a for loop does but in a more understandable form, just like forEach.
Ex. of for loop
for(var i = 0; i<arr.length; i++){
(code goes here)
}
Ex. of a map
var examples = example.map(function(ex){
(code goes here)
});
As you can see, map is much easier to read than for loop but it is a bit longer, but that shouldn’t be much of a problem. However, there are going to be differences between map and forEach.
Some of these main differences between map and forEach would include things like speed and what is returned in the console. For starters, forEach is slower. Not that is a bad thing if you are just using them for fun, school, etc. However it would be better to use map because it’s faster and because map will return a new array, which you can use to do other things.