JavaScript Array forEach() method iterates over array elements, in ascending index order, executing a provided callback function for each one.
The forEach() method does not return a value (always returns undefined) and is primarily used for performing side effects, such as logging, DOM manipulation, or updating external state.
const arr = [5, 10, 15, 20, 25]; arr.forEach(element => console.log(element)); // Output: // 5 // 10 // 15 // 20 // 25
In this code, we log each array value individually in ascending order. You can see that we don’t need to use an array index to print the value or for…of loop. Here, the loop construct is abstract.
Syntax
array.forEach(callback(currentValue, index, array), thisArg)
Parameters
Argument | Description |
callback (required) | It represents a function to execute for each element.
It is invoked for each element with three arguments:
|
thisArg (optional) |
It is a value to use as “this” when executing the callback. |
Using all callback arguments
Let’s pass a callback with all three arguments that accesses the array reference and modifies it in place.
const numbers = [11, 21, 19]; numbers.forEach((value, index, arr) => { arr[index] = value * 2; // Mutates the original array }); console.log(numbers); // Output: [ 22, 42, 38 ]
In this code, the “value” is a single element of the “arr” at a time, and “index” starts with 0.
Essentially, we are transforming the array by modifying its elements directly.
With “thisArg” for Context
Let’s explicitly set “this” inside the callback by passing a thisArg. Make sure that you don’t use an arrow function because arrow functions don’t have their own this—they inherit this from their enclosing scope, ignoring the thisArg.
const obj = { multiplier: 3 }; const numbers = [11, 21, 19]; numbers.forEach(function (value) { console.log(value * this.multiplier); }, obj); // Output // 33 // 63 // 57
In this code, “thiArg” is an “obj” that has a “multiplier” property. Now, when the callback is not an arrow function, it is a normal function, and this.multiplier refers to an object’s multiplier property.
So, this.multiplier is 3 and the output is 11*3 = 33, 21*3 = 63, and 19*3 = 57.
Sparse arrays
If your input array contains holes, it will skip that index and will not print for that hole when you log it.
const sparse_array = [19, , 21]; // Hole at index 1 sparse_array.forEach((value, index) => { console.log(`Index ${index}: ${value}`); }); // Output: // Index 0: 19 // Index 2: 21
In the above sparse array, the length will be 3, but the second index is a hole, so the callback is not called for holes. That’s all!