ES6 Array methods forEach and map
The ES6 Array methods forEach and Map help you go through arrays very efficiently and print it or use it for anything you need. First off all the forEach method lets you is used to iterate through dynamic memory buffers also known as arrays. Traditional for loops in most object oriented programming languages use place-holding variables that are declared and defined within the for loop’s conditional brackets. The syntax looks like this:
for (var i = 0; i < array.length; i++) {
// your code here
// use array[i]
};It kind of seems like a lot, does it not? The forEach() method makes it to were you don’t have to declare a place-holder.
array.forEach(number){
// your code here
// use number
};The second example is much more elegant and easier to read. This is why it is highly preferable to the traditional for loop.
map() function
The map function is very similar to the forEach() method, except it does not actually change the memory buffer in-place. Instead, it returns a “deep copy” of sorts. Here is the syntax of map()
var newArray = array.map(number){
number.toString();
};This example converts each number to a string and saves a deep copy into the variable newArray.