Foreach() is most likely the first es6 helper you will learn to use. Map() is another. They both are pretty similar, but I'll explain the differences with examples below.
Once you get used to writing forEach()
loops, you will forget all about the for
loop. It'll be like a bad memory. With es5, a for
loop looks like this:
jslet bands = ['sonic youth', 'system of a down', 'animal collective'];for(let x=0; x < bands.length; x++ ) {console.log(bands[x]);}
When you use forEach()
, we write less code, and it's easier to read imo. There is less logic to write when using forEach()
. We pass an anon function that iterates through the array.
The main difference between forEach()
and map()
is that forEach()
iterates over a list, that's it. It doesn't return anything. Map()
iterates over the list, transforms them, and returns a new array. In the example below, I am making the data uppercase:
jslet bands = ['sonic youth', 'system of a down', 'animal collective'];bands.forEach(function(band) {console.log(band);});//returns "sonic youth", "system of a down" ... in console//map()let uppercase = bands.map(function(band) {return band.toUpperCase();});console.log(uppercase);//returns ["SONIC YOUTH", "SYSTEM"...] in console.
view all posts