JavaScript Array forEach() method


The forEach() method in JavaScript is used to execute a provided callback function once for each element in an array. This method is a part of the Array prototype and provides a convenient way to iterate over array elements without the need for a traditional for loop.

Syntax:

array.forEach(callback(currentValue, index, array), thisArg)
  • callback: A function that is executed for each element in the array. It can accept three parameters:
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array forEach() was called upon.
  • thisArg (optional): A value to use as this when executing the callback function.

Return Value:

  • Undefined: The forEach() method returns undefined. It does not create a new array or return any values.

Key Points:

  • Iterates over each element: The forEach() method calls the provided function once for each element in the array.
  • Modifies original array: It does not modify the original array unless explicitly done within the callback.
  • Cannot be broken: Unlike traditional loops, you cannot use break or return to stop the iteration. To exit early, you'll need to use a different loop construct.

Example 1: Basic usage

let fruits = ['apple', 'banana', 'orange']; fruits.forEach(function(fruit) { console.log(fruit); }); // Output: // apple // banana // orange

Example 2: Using index and array parameters

let numbers = [10, 20, 30]; numbers.forEach(function(number, index, array) { console.log(`Element at index ${index} is ${number}`); }); // Output: // Element at index 0 is 10 // Element at index 1 is 20 // Element at index 2 is 30

Example 3: Using an arrow function

let animals = ['cat', 'dog', 'rabbit']; animals.forEach((animal) => { console.log(animal.toUpperCase()); }); // Output: // CAT // DOG // RABBIT

Example 4: Modifying elements within the callback

let numbers = [1, 2, 3]; numbers.forEach((number, index) => { numbers[index] = number * 2; }); console.log(numbers); // [2, 4, 6] (original array modified)

Example 5: Using thisArg

let obj = { multiplier: 2, }; let numbers = [1, 2, 3]; numbers.forEach(function(number) { console.log(number * this.multiplier); }, obj); // Output: // 2 // 4 // 6

Summary:

  • forEach() is a convenient method for iterating over elements in an array, allowing you to apply a function to each element.
  • It provides access to the current element, its index, and the original array if needed.
  • Since forEach() returns undefined, it is primarily used for executing side effects, like logging or modifying data, rather than for generating new arrays or collecting results.