8 Neat Examples with forEach() in JavaScript
The Array#forEach()
function is a common tool tool to iterate through arrays. However, with the help of some other language features, forEach()
can do a lot more than just print every value in an array. In this tutorial, you'll see 10 examples demonstrating common patterns with forEach()
.
Example 1: The Basics
The forEach()
function's first parameter is a callback function that JavaScript executes for every element in the array.
// Prints "a", "b", "c"
['a', 'b', 'c'].forEach(v => {
console.log(v);
});
Example 2: Modifying the Array
Generally speaking, you shouldn't modify the array using forEach()
. If you want to modify the array, you should use Array#map()
instead. But it is possible to modify the array using forEach()
, and you may run into code that does so. Here's an example of converting each array element to upper case using forEach()
.
const arr = ['a', 'b', 'c'];
arr.forEach((v, i) => {
arr[i] = v.toUpperCase();
});
arr; // ['A', 'B', 'C']
Example 3: Object Keys
The Object.keys()
function returns an array that contains an object's keys. If you want to iterate through an object's keys using forEach()
, you should use Object.keys()
.
const obj = {
a: 1,
b: 2,
c: 3
};
// Prints "a", "b", "c"
Object.keys(obj).forEach(key => console.log(key));
Example 4: Object Keys and Values
You can iterate through an object's keys using forEach()
and Object.keys()
. But what about iterating through both keys and values simultaneously? That's what the Object.entries()
function is for. Given an object, Object.entries()
returns an array of [key, value]
pairs.
const obj = {
a: 1,
b: 2,
c: 3
};
// Prints "a 1", "b 2", "c 3"
Object.entries(obj).forEach(([key, value]) => {
console.log(key + ' ' + value)
});
Example 5: Nested Arrays and flat()
The forEach()
function will iterate through the top-level array. If you have arrays of arrays, you need to use Array#flat()
to flatten nested arrays first.
const arr = ['a', ['b', 'c'], [['d', ['e']]]];
// Prints "a", "b", "c", "d", "e". `3` is the maximum depth for flattening
arr.flat(3).forEach(v => console.log(v));
Example 6: Adding Elements to the Array
The forEach()
function sets the elements that will be called before calling your callback for the first time. In other words, if you add elements to the array in your forEach()
callback, JavaScript will not call your callback on the new elements. No need to worry about causing an infinite loop by adding elements to your array in your forEach()
callback.
const arr = ['a', 'b', 'c'];
// Prints "a", "b", "c", even though each callback invocation adds
// a new element to the array.
arr.forEach(v => {
arr.push(v.toUpperCase());
console.log(v);
});
Example 7: thisArg
The forEach()
function actually takes 2 parameters, callback
and thisArg
. The thisArg
function lets you set the value of this
in your callback
. The thisArg
argument is handy for functions that rely on this
, like the Stack
class in the below example.
const arr = ['a', 'b', 'c'];
class Stack {
constructor() {
this._arr = [];
}
push(v) {
this._arr.push(v);
}
pop() {
return this._arr.pop();
}
}
const stack = new Stack();
// Without `thisArg`, would throw an error
arr.forEach(stack.push, stack);
// Equivalent:
arr.forEach(v => stack.push(v));
// Also equivalent:
arr.forEach(stack.push.bind(stack));
Example 8: Array Holes
JavaScript arrays have some quirks. Specifically, the array ['a',, 'c']
is different than the array ['a', undefined, 'c']
, even though arr[1] === undefined
in both cases. In ['a',, 'c']
, arr[1]
is called an "array hole".
The forEach()
function skips array holes. To get forEach()
to treat array holes as undefined
, you first need to get rid of array holes using Array.from()
.
const arr = ['a',, 'c'];
// Prints "a", "c"
arr.forEach(v => console.log(v));
// Prints "a", "undefined", "c". `Array.from()` removes holes
Array.from(arr).forEach(v => console.log(v));