Arrays are sometimes referred to as List-like objects.
forEach vs. for Loops
forEach is an array method, just like push()
or pop()
, that is simply a loop that accesses each item in an array.
Example
const fruits = ['apple', 'pear', 'cherry'];
let capitalizedFruits = [];
fruits.forEach( fruit => {
let capitalizedFruit = fruit.toUpperCase();
capitalizedFruits.push(capitalizedFruit);
});
console.log(capitalizedFruits); // output: 'APPLE', 'PEAR', 'CHERRY'
forEach()
is better than a for loop in every way.
Except for one con; you can’t break out of the iteration early before the end of the array. If you come across this case, use for
or while
instead.
forEach() Parameters
As you can see from the example above, forEach()
takes a callback function as an argument with the an array item
variable as its parameter.
array.forEach(currentItem => {...});
But the callback also takes more parameters, such as the index of the current array item, and the whole array itself.
array.forEach( function callback(currentItem, index, array) {
...
});
Example
const fruits = ['apple', 'pear', 'cherry'];
let capitalizedFruits = [];
fruits.forEach( (fruit, index) => {
let capitalizedFruit = fruit.toUpperCase();
capitalizedFruits.push(capitalizedFruit);
console.log(`${index + 1}. ${fruit}`);
});
/* output:
1. APPLE
2. PEAR
3. CHERRY
*/