Array.forEach()

The Array.forEach() method in JavaScript is used to execute a provided callback function once for each array element. It is commonly used for performing side effects like logging or modifying external variables but does not return a new array or change the original array.

Syntax

</>
Copy
forEach(callbackFn)
forEach(callbackFn, thisArg)

Parameters

ParameterDescription
callbackFnA function to execute on each element of the array. It takes three arguments:
  • currentValue: The current element being processed.
  • index (Optional): The index of the current element.
  • array (Optional): The array being iterated.
thisArgOptional. A value to use as this when executing callbackFn.

Return Value

The forEach() method does not return a value. It always returns undefined.


Examples

1. Iterating Over Array Elements

This example demonstrates how to iterate over array elements using the forEach() method.

</>
Copy
const numbers = [10, 20, 30];

numbers.forEach((num) => {
    console.log(num);
});

Output

10
20
30

Here, the callbackFn is executed for each element of the array, logging its value to the console.

2. Accessing Index and Array

The callback function can also access the index and the original array.

</>
Copy
const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit, index, array) => {
    console.log(`Index: ${index}, Fruit: ${fruit}, Array: ${array}`);
});

Output

Index: 0, Fruit: apple, Array: apple,banana,cherry
Index: 1, Fruit: banana, Array: apple,banana,cherry
Index: 2, Fruit: cherry, Array: apple,banana,cherry

This demonstrates the use of all three arguments in the callback function: currentValue, index, and array.

3. Using thisArg

The thisArg parameter allows you to specify the value of this inside the callback function.

</>
Copy
const multiplier = {
    factor: 2,
};

const numbers = [1, 2, 3];

numbers.forEach(function (num) {
    console.log(num * this.factor);
}, multiplier);

Output

2
4
6

Here, the thisArg is set to the multiplier object, allowing the callback function to access this.factor.

4. Modifying External Variables

The forEach() method can be used to modify variables outside of its scope.

</>
Copy
const numbers = [1, 2, 3];
let sum = 0;

numbers.forEach((num) => {
    sum += num;
});

console.log(sum);

Output

6

In this example, the variable sum is updated during each iteration of the forEach() loop.