Looping with forEach
Learn to traverse an array with forEach and the callback idea.
Traversing an array with forEach
To traverse all elements of an array you use the forEach method. forEach runs a callback function for each element.
Example: fruits.forEach(fruit => console.log(fruit)); prints each element of the array in order.
forEach does not return a new array; its return value is undefined. So it is not suitable for collecting results, only for processing elements one by one.
fruit => console.log(fruit) is a short way to write a function (an arrow function): the left of the arrow is the parameter, the right is the expression to run. It does the same as function (fruit) { console.log(fruit); }; you will cover it in detail at the intermediate level.
The three parameters of forEach
The callback function can take three parameters: (element, index, array). Only the first is required; you use the others as needed.
Example: fruits.forEach((fruit, i) => console.log(i + ". " + fruit)); prints each element together with its index.
The second parameter is the index, the third is the array itself. Names do not matter; the order does.
Exercise Print the fruits array with forEach
Create an array named fruits with at least three fruit strings. Use forEach to print each element with console.log.
Show example solution
Write the array with square brackets, then pass a callback to forEach.
Example solution:
const fruits = ["apple", "pear", "banana"];
fruits.forEach(fruit => console.log(fruit));
Test yourself
-
How many times does console.log run in this code?
const nums = [10, 20, 30]; nums.forEach(n => console.log(n));- 1
- 3
- 0
- 2
Show answer
3 — Correct. forEach calls the callback for each element; 3 elements means 3 calls.
-
Print each element with forEach
const fruits = ["apple", "pear", "banana"]; fruits.forEach(fruit => console.log(____));Show answer
const fruits = ["apple", "pear", "banana"]; fruits.forEach(fruit => console.log(fruit)); -
Match the forEach callback parameters
- 1st parameter
- element value
- 2nd parameter
- element index
- 3rd parameter
- the array itself