forEach: Loop Without the Loop

Grade 10, page 2 of 12. A one-minute read.

The simplest array method is forEach. It calls your callback once for each item in the array:

JavaScript
const fruits = ["mango", "pineapple", "banana"];

fruits.forEach((fruit) => {
  console.log(`I love ${fruit}! 🍽️`);
});

It prints

I love mango! 🍽️
I love pineapple! 🍽️
I love banana! 🍽️

Your callback actually receives up to three arguments: the item, its index, and the whole array. Usually you just need the first one or two:

JavaScript
const fruits = ["mango", "pineapple", "banana"];

fruits.forEach((fruit, index) => {
  console.log(`${index + 1}. ${fruit}`);
});

It prints

1. mango
2. pineapple
3. banana

forEach is basically the same as a for...of loop, just written as a method. One difference: you can't use break to stop a forEach early. It always visits every item. If you need to stop early, use a regular loop (or find/some, which you'll meet shortly).

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning