Javascript’s forEach method is one of its basic array methods, and it’s used all the time. It does as its name suggests, and performs a function for each element of an array:
const myList = ["a", "b", "c"];
myList.forEach(item => console.log(item));
// "a"
// "b"
// "c"
In the function above, I only accessed one argument, item
. However, forEach actually makes 3 arguments available to its callback function if you want them:
const myList = ["a", "b", "c"];
myList.forEach((item, index, list) => {
console.log(item, index, list);
});
// "a", 0, ["a", "b", "c"]
// "b", 1, ["a", "b", "c"]
// "c", 2, ["a", "b", "c"]
ForEach cannot be stopped early
This is the major gotcha with forEach: it will always call your function once per array element, it cannot be stopped. Put another way, you cannot break
a forEach. Consider this case, where you want to abort a for
loop early:
const myList = ["a", "b", "c"];
// a traditional for loop can be broken early
for (let item of myList) {
console.log(item);
if (item === "a") {
console.log("a found, terminating loop");
break;
}
}
// "a"
// "a found, terminating loop"
If you use forEach
, you can’t stop the loop:
const myList = ["a", "b", "c"];
myList.forEach((item) => {
console.log(item);
if (item === "a") {
console.log("a found, terminating loop");
return;
}
});
// "a"
// "a found, terminating loop"
// "b"
// "c"
Other notes about forEach
ForEach is not designed for use with async functions, even if you properly declare it as async
and use await
within the function body. This isn’t too surprising given how javascript generally handles async operations, but it is strange to see async / await
not having their intended effects. For a full example of this behavior and a few more potential gotchas, check out the Moz docs page for forEach.