CodeBlanks Logo Icon CodeBlanks

forEach

Learn side-effect loops with .forEach.

The forEach method

The forEach method calls a function for each element of an array and produces a side effect. Unlike map it does not return a new array; the result is undefined.

The syntax is array.forEach(fn). Here fn is the function called for each element. Typical uses are printing, saving to a file, or updating a counter. For transformations use map; forEach is only for side effects.

Example: ['apple','pear','banana'].forEach(f => console.log(f)) prints each fruit on its own line. Since forEach returns undefined, assigning it to a variable makes no sense.

forEach versus map

It is easy to confuse forEach and map. Both let you walk each element; the difference is the return value. map returns an array and is for transformations. forEach returns undefined and is for side effects.

If you do not use the array map returns, forEach is the better fit. Conversely, assigning forEach's result or chaining it is wrong, because the result is undefined.

Example: [1,2,3].forEach(n => console.log(n)) prints each number. [1,2,3].map(n => n * 2) returns [2,4,6]. Which method to pick depends on whether you will use the result.

Practice Print the scores

Define an array of scores [85, 72, 90]. Use forEach to print each score as "Score: X" (X is the score) with console.log. You can use a template literal: `Score: ${n}`.

Starter code

index.js
const scores = [85, 72, 90];
// Print each score as 'Score: X'

Sample solution

index.js
const scores = [85, 72, 90];
scores.forEach(n => console.log('Score: ' + n));

Expected output

Score: 85
Score: 72
Score: 90

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the forEach parts

Term Meaning
array.forEach(fn) The call
fn Function called per element
side effect What forEach produces
undefined What forEach returns

2 What does forEach return?

  • true
  • A new array
  • undefined Correct answer
  • Number of elements

Explanation: forEach returns undefined, not an array.

3 Print the list

Question
const fruits = ['elma','armut','muz'];
fruits.forEach(f => console.____(f));
Answer
const fruits = ['elma','armut','muz'];
fruits.forEach(f => console.log(f));

Explanation: console.log(f) prints each fruit on its own line.

All lessons in Beginner