Chapter VIII · Arrays

forEach

The forEach method executes a provided callback function once for each array element.

01 How It Works

Think of an inspector walking down a line of boxes checking each one individually.

forEach iterates through items for side effects; it does not return a new array.

example.js
["a", "b", "c"].forEach(item => console.log(item));
  1. 1. Call .forEach() on an array instance.

  2. 2. Pass an execution callback function.

  3. 3. Perform side-effect tasks per item.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
const numbers = [10, 20];
numbers.forEach(n => console.log(n * 2));

Key Takeaway

Use forEach for performing side-effect operations rather than transforming data.

Related Concepts