forEach with callbacks
- Node.js course
- Beginner
- Lesson 79/116
- 5 min
Learn the callback pattern with .forEach.
forEach with callbacks
The forEach method is one of the best-known examples of a function that takes a callback. It calls your callback for each element, so you can walk all items without writing a loop.
Syntax: array.forEach(cb). Here cb is the callback called for each element. The forEach you saw earlier is the same idea; the arrow function is given as a callback.
Example: [10, 20, 30].forEach(n => console.log(n)). Here n => console.log(n) is the callback; forEach calls it for each element. The result is undefined because forEach is for side effects.
The callback takes three parameters
The callback forEach calls can take three parameters: (element, index, array). Most of the time only element is used; but when you need the position, the index parameter helps.
Example: ['a', 'b', 'c'].forEach((letter, i) => console.log(i + ': ' + letter)). This writes the position next to each letter: 0: a, 1: b, 2: c. The index parameter gives the position.
The third parameter, array, is rarely used; it lets the callback reach the whole array. Most of the time the first two parameters are enough.
Practice Print the list with indices
Define an array of fruits ['apple', 'pear', 'banana']. Use forEach with a callback that takes two parameters and prints i + ': ' + f (i is the index, f the fruit) with console.log.
Starter code
// Print the fruits with indices using forEachSample solution
const fruits = ['apple', 'pear', 'banana'];
fruits.forEach((f, i) => console.log(i + ': ' + f));Expected output
0: apple 1: pear 2: banana
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the forEach callback parts
| Term | Meaning |
|---|---|
forEach |
Method using a callback |
cb |
Callback parameter |
n => console.log(n) |
Arrow function passed as callback |
undefined |
forEach's return value |
2 What is the second parameter of forEach's callback?
- Element
- Array
- Index Correct answer
- Length
Explanation: the second parameter is index and gives the position.
3 Print with the index
const fruits = ['elma','armut','muz'];
fruits.forEach((f, i) => console.log(i + ': ' + ____));
const fruits = ['elma','armut','muz'];
fruits.forEach((f, i) => console.log(i + ': ' + f));
Explanation: i + ': ' + f writes lines like '0: apple'.