# 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.

  1. The item from the Array
  2. The index number of the current item.
  3. 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
**/
1
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']
1
2
3
4
5

Back to Week 4 main page

Last Updated: 6/13/2020, 11:30:19 PM