# Array Loops
# Array.forEach()
If you want to loop through an array, there is a built-in method for doing so, called forEach
. The method has one required parameter - a function. It will call this function once for each item in the Array.
When it calls the function, it will pass three things to the function.
- The item from the Array
- The index number of the current item.
- A copy of the Array which can be used to do comparisons.
The three items will ALWAYS come in that order. You can name the three variables whatever you like.
let beers = ["Corona", "Headstock", "Heineken"];
beers.forEach(function(item, index, arr) {
console.log(index, item);
});
/** outputs
0 Corona
1 Headstock
2 Heineken
**/
2
3
4
5
6
7
8
9
# Array.map()
The map
method works similarly to the forEach
method. It loops once for each item in the Array. It calls a function (which you provide) each time it loops. It provides the same three values to the function each time it is called.
The difference is that while the forEach
method returns undefined
, the map
method returns a new array built out of the return values from the function it called.
Because it called the function once for each item in the Array, it means that the new Array will always be the exact same length as the original array.
let cheeses = ["Gouda", "Cheddar", "Brie"];
let newArr = cheeses.map(function(item, index, arr) {
return item.substr(1, 2); //return the 2nd letter from item
});
console.log(newArr); // ['o', 'h', 'r']
2
3
4
5