forEach()
forEach()
Section titled “forEach()”Introduction
Section titled “Introduction”forEach() executes a function for each element in the array. It’s used for side effects (logging, updating external state) rather than creating new values.
Syntax
Section titled “Syntax”array.forEach((element, index, array) => { // side effect});Example
Section titled “Example”const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`);});// 0: apple// 1: banana// 2: orangeforEach vs map
Section titled “forEach vs map”// Use forEach for side effectsfruits.forEach(fruit => console.log(fruit));
// Use map for transformationconst lengths = fruits.map(fruit => fruit.length);Summary
Section titled “Summary”- Iterates over each element
- Returns
undefined— cannot chain - Cannot break or continue (use for…of instead)
- Use for side effects, not transformations