The three JavaScript loop styles, which are forEach, map, and for...of, look interchangeable right up to the moment you try to use the result of one of them, or to stop early inside another. This lesson lines them up against the same data so that you can pick by behaviour instead of by habit.
The previous lesson in this module covered "Changing Arrays: push, pop, splice and More", and the next lesson in this module is about "filter, find and reduce: The Search-and-Aggregate Trio".
What does map give you that forEach does not?
map builds a new array out of whatever your callback returns. forEach runs your callback purely for its side effects and hands back undefined. If your callback computes a value and you then throw that value away, then you used forEach where map was the right tool.
const users = [
{ name: 'Ada', role: 'admin' },
{ name: 'Linus', role: 'dev' },
];
const names = users.map(function (user) {
return user.name;
});
console.log(names); // [ 'Ada', 'Linus' ]
const roles = users.map(function (user) {
return user.role.toUpperCase();
});
console.log(roles); // [ 'ADMIN', 'DEV' ]
Neither version touches the original array. map returns a new array of the same length, and forEach returns nothing for you to keep. That single difference is the fastest way to choose between them.
Why can you not break out of a forEach?
Because forEach has no way to be told to stop. break and continue are syntax errors inside the callback, and return only leaves the callback and not the loop. That makes forEach a poor fit for searching, where you want to stop at the first hit.
const rows = ['a', 'b'];
const result = rows.forEach(function (row) {
return row;
});
console.log(result); // undefined
const copied = rows.map(function (row) {
return row;
});
console.log(copied); // [ 'a', 'b' ]
The two console.log lines make the return-value difference concrete. forEach gave you undefined, and map gave you a new array. When you need to stop at the first match, use find from the next lesson, or use a for...of loop.
When is for-of the better choice?
for...of gives you the value inside a real loop, so break, continue, and return all behave in the way that you expect. Reach for it when the loop body does more than transform one value, such as when it logs, when it calls a function, when it waits for something, or when it needs an early exit.
const labels = ['one', 'two', 'three'];
for (const label of labels) {
if (label === 'two') {
break;
}
console.log('kept: ' + label);
}
That prints kept: one and then stops. Swap break for continue and the loop skips the rest of the body for that item but carries on with the next one. It is also worth knowing that for...of works on anything that you can iterate over, such as strings, Set objects, Map objects, and the entries() helper, so it is not limited to arrays.
How do you get the index while looping?
map and forEach pass the index as the second argument to your callback. for...of does not, because it only gives you values. When you need both, you have two options. You can use the index that the callback receives, or you can iterate over entries().
const pairs = ['x', 'y', 'z'];
pairs.forEach(function (value, index) {
console.log(index, value);
});
for (const entry of pairs.entries()) {
console.log(entry[0], entry[1]);
}
Both loops print 0 x, 1 y, and 2 z. The entries() helper produces a list of [index, value] pairs, so each entry gives you both parts. The square-bracket pattern is called destructuring, and the destructuring module later in this tutorial covers it properly. For now, just read entry[0] as the index and entry[1] as the value.
Do any of them run faster?
For arrays of a similar size the differences are small enough that you should choose based on how easy the code is to read. Two practical notes still matter. map allocates a new array on every call, while forEach allocates nothing at all, so forEach is the cheaper choice when you only need to trigger an action. And chaining three methods such as filter().map().filter() means three separate passes over the data. That is perfectly fine for a few hundred items, and it is worth collapsing into a single reduce once you are dealing with thousands.
Why does passing a function straight to map break?
The callback receives more arguments than you might expect. It gets the value, the index, and the whole array. Passing a function that happens to accept a second parameter can therefore change its behaviour, and map(parseInt) is the classic example of this.
console.log(['1', '2', '3'].map(parseInt));
// [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map(function (text) {
return parseInt(text, 10);
}));
// [ 1, 2, 3 ]
parseInt takes a second argument for the base of the number, so the index 1 becomes the base, and parseInt('2', 1) makes no sense at all. The fix is to wrap it in a function of your own, so that only the value is passed. If a function that you give to map has a second parameter, check what that parameter means before you assume that the result is about the array.
Which loop style should you reach for?
| Style | Use it when | Returns | Can stop early? |
|---|---|---|---|
forEach | You only need a side effect: logging, pushing, drawing | undefined | No |
map | You need a new array of transformed values | New array | No |
for...of | You need control flow, an index, or the source is not an array | Whatever your loop body produces | Yes, with break |
One tie-breaker settles most arguments. If you are writing a function that returns an array of transformed values, use map. If the function returns nothing and performs an action, use forEach. If the body needs an early exit or needs the index, use for...of. And if the callback body needs a nested if just to skip some work, then you usually wanted filter or find instead.
Try it yourself: take an array of three products, where each one has a name, a price, and a stock number. Write the same task three ways. Print each product name with forEach, build an array of prices with map, and print only the products that have stock above zero by using for...of with continue. Then write discount(products, rate) so that it returns a new array of objects with the same names and prices reduced by the given rate, using map. Print the original array afterwards to confirm that none of its prices changed.