forEach
forEach runs a function once for every item in an array, which is the first step from writing loops to passing them around.
forEach takes a function and calls it per item, with the item, its index and the array. It always returns undefined, so it is for doing something with each item rather than producing a new value.
EXERCISE
1Handing a Function to a Loop
Instead of writing the loop yourself, you hand forEach the work you want done and it does the walking.
The same job, two ways:
const names = ["Ada", "Grace", "Alan"];
// Writing the loop yourself:
for (const name of names) {
console.log(name);
}
// Handing the work to forEach:
names.forEach(function (name) {
console.log(name);
});
// And with an arrow, which is how you will usually see it:
names.forEach((name) => console.log(name));
All three print the same three lines.
What is actually happening:
const names = ["Ada", "Grace"];
names.forEach((name) => {
console.log(`Called with ${name}`);
});
// Called with Ada
// Called with Grace
// forEach called your function twice, once per item,
// passing the item in as the argument each time.
The function you pass in is called a callback: a function you hand to another function to be called later.
It works on an array of objects just the same:
const users = [
{ name: "Ada", active: true },
{ name: "Grace", active: false },
];
users.forEach((user) => {
console.log(`${user.name}: ${user.active ? "active" : "inactive"}`);
});
// Ada: active
// Grace: inactive
The shift here is small in syntax and large in what it opens up. Once a loop can take a function as an argument, the loop itself becomes reusable and only the work changes. Every method in the rest of this unit follows the same pattern, so getting comfortable with the callback shape now pays off six times over.
EXERCISE
2The Three Arguments Your Callback Can Take
forEach passes three things to your function, and you take as many as you need from the left.
Item, index, and the whole array:
const names = ["Ada", "Grace", "Alan"];
names.forEach((name, index, array) => {
console.log(`${index}: ${name} (of ${array.length})`);
});
// 0: Ada (of 3)
// 1: Grace (of 3)
// 2: Alan (of 3)
Take only what you need:
// Just the item, which is most common:
names.forEach((name) => console.log(name));
// Item and index:
names.forEach((name, i) => console.log(`${i + 1}. ${name}`));
// 1. Ada
// 2. Grace
// 3. Alan
// The third argument is rarely useful, since you usually
// already have the array in a variable.
The names are yours to choose:
const scores = [90, 72];
scores.forEach((score, position) => {
console.log(`Score ${position} is ${score}`);
});
// Score 0 is 90
// Score 1 is 72
// `score` and `position` are just parameter names.
// forEach passes the values by position, not by name.
A real use, updating each object in a list:
const cart = [
{ name: "Tea", price: 40, qty: 2 },
{ name: "Coffee", price: 120, qty: 1 },
];
cart.forEach((item) => {
item.lineTotal = item.price * item.qty;
});
console.log(cart[0].lineTotal); // 80
console.log(cart[1].lineTotal); // 120
That works because objects are shared by reference, so changing item inside the callback changes the object in the array.
Pro Tip: A callback is handed everything the method offers, whether or not your function names it.
forEach,map,filterand the rest all pass the item, the index and the array, and your function simply ignores the ones it did not declare. That is harmless when you write the callback yourself, and it is the reason["10","20","30"].map(parseInt)returns[10, NaN, NaN]:parseInttakes a second argument, so it reads the index as one. Whenever you pass an existing function in by name rather than writing an arrow, check what it does with a second argument.
EXERCISE
3What forEach Cannot Do
forEach always returns undefined and cannot be stopped early, and knowing both limits tells you when to use something else.
It returns undefined, always:
const numbers = [1, 2, 3];
const result = numbers.forEach((n) => n * 2);
console.log(result); // undefined
// The callback returned 2, 4 and 6, and forEach threw them away.
// If you want those values, you want `map`, which is the next lesson.
You cannot break out of it:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((n) => {
if (n > 3) {
// break; SyntaxError: Illegal break statement
return; // this only ends THIS call, not the loop
}
console.log(n);
});
// 1
// 2
// 3
// 4 and 5 were still visited, their callbacks just returned early.
When you need to stop, use a real loop:
const numbers = [1, 2, 3, 4, 5];
for (const n of numbers) {
if (n > 3) break;
console.log(n);
}
// 1
// 2
// 3
// and the loop genuinely stopped.
Choosing:
// Doing something with each item, no result needed? forEach.
users.forEach((user) => console.log(user.name));
// Need a new array out of it? map, filter, and the rest.
// Need to stop partway? for-of with break.
// Need to skip the rest of one turn? return inside forEach works fine.
Pro Tip:
forEachis for side effects: printing, updating, sending. The moment you find yourself collecting results into a variable you declared just above the loop, one of the methods in the next few lessons does that job in one line, and says what it is doing in its name.
