JavaScript Array forEach() Method

The JavaScript Array.forEach() method executes a provided function once for each element in an array, in ascending order. It does not return anything (i.e., undefined) and simply allows you to iterate through the array to perform actions on its elements.

For example, array.forEach(callback) is useful when you need to run a function on every element of the array, but you don’t need to return or modify the array itself.

Syntax

The syntax for the Array.forEach() method is:

plaintext
array.forEach(callback(element, index, array), thisArg)

Parameters

The Array.forEach() method accepts two parameters:

  • callback (Required): A function that is executed on each element of the array. It takes the following arguments:
    • element: The current element being processed.
    • index (Optional): The index of the current element.
    • array (Optional): The array being traversed.
  • thisArg (Optional): Value to use as this when executing the callback function. If not provided, undefined is used.

Return Value

The forEach() method returns undefined, as its purpose is to iterate over the array and execute a side effect for each element.

Examples of JavaScript Array.forEach() Method

Example 1: Iterating Over an Array

You can use forEach() to execute a function on each element of the array.

javascript
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num));
// Output: 1 2 3 4 5

Explanation: The forEach() method logs each element of the numbers array to the console.

Example 2: Using forEach() with Index and Array

You can access both the index and the array inside the callback function.

javascript
const numbers = [10, 20, 30];
numbers.forEach((num, index, array) => {
 console.log(`Element: ${num}, Index: ${index}, Array: ${array}`);
});
// Output: 
// Element: 10, Index: 0, Array: 10,20,30
// Element: 20, Index: 1, Array: 10,20,30
// Element: 30, Index: 2, Array: 10,20,30

Explanation: The forEach() method gives access to the element, index, and the entire array during iteration, allowing you to work with each element’s index and context.

Example 3: Modifying an External Variable Inside forEach()

Although forEach() doesn’t return a value, you can modify variables outside the loop within the callback.

javascript
let sum = 0;
const numbers = [5, 10, 15];
numbers.forEach(num => sum += num);
console.log(sum);  // Output: 30

Explanation: The forEach() method is used to sum the values of the numbers array and update the sum variable.

Example 4: Using forEach() with thisArg

You can provide a custom this context using the thisArg parameter.

javascript
const context = { multiplier: 2 };
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
 console.log(num * this.multiplier);
}, context);
// Output: 2 4 6

Explanation: The thisArg parameter is used to set this to the context object, allowing the forEach() method to use the multiplier property while iterating over the array.

Example 5: Exiting a forEach Loop

The forEach() method doesn’t support breaking out of the loop early. Instead, you can use a return statement to skip the current iteration, but it will continue to process the rest of the array.

javascript
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
 if (num === 3) return;
 console.log(num);
});
// Output: 1 2 4 5

Explanation: The forEach() method skips the element 3 but continues to process the rest of the elements in the array.

Example 6: Using forEach() on an Empty Array

When the forEach() method is called on an empty array, the callback function is not executed.

javascript
const emptyArray = [];
emptyArray.forEach(num => console.log(num));
// No output

Explanation: Since the array is empty, the forEach() method doesn’t execute the callback function.

JavaScript

3696

385

Related Articles