JavaScript forEach() method


The forEach() method in JavaScript is used to execute a provided function once for each element in an array. It is particularly useful for iterating over arrays when you need to perform some action on each element, such as logging values, modifying elements, or performing operations without returning a new array.

Key Characteristics of forEach():

  1. No Return Value:

    • Unlike some other array methods, forEach() does not return a new array or any value. Its purpose is solely to execute a function for its side effects (such as modifying elements or logging to the console).
  2. Callback Function:

    • The forEach() method takes a callback function as an argument. This callback function is executed on each element of the array.
  3. Parameters of the Callback Function:

    • The callback function can accept up to three parameters:
      1. Current Value: The value of the current element being processed.
      2. Index (Optional): The index of the current element.
      3. Array (Optional): The array that forEach() was called upon.
  4. No Break or Continue:

    • You cannot break out of a forEach() loop using break or continue like you can with a traditional for loop. If you need such control, a for, for...of, or for...in loop might be more appropriate.

Syntax:

array.forEach(function(currentValue, index, array) { // code to execute for each element });

Example 1: Simple Iteration

let fruits = ["Apple", "Banana", "Cherry"]; fruits.forEach(function(fruit) { console.log(fruit); }); // Output: // Apple // Banana // Cherry
  • Explanation: In this example, the forEach() method iterates over each element in the fruits array and logs it to the console.

Example 2: Using the Index Parameter

let fruits = ["Apple", "Banana", "Cherry"]; fruits.forEach(function(fruit, index) { console.log(`${index}: ${fruit}`); }); // Output: // 0: Apple // 1: Banana // 2: Cherry
  • Explanation: Here, the index parameter is used to log both the index and the corresponding fruit in the array.

Example 3: Modifying Elements (Note: Doesn't Modify the Original Array Directly)

let numbers = [1, 2, 3, 4, 5]; let doubledNumbers = []; numbers.forEach(function(number) { doubledNumbers.push(number * 2); }); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
  • Explanation: In this example, forEach() is used to iterate over the numbers array, double each value, and push it to a new array doubledNumbers.

Example 4: Accessing the Original Array

let numbers = [1, 2, 3, 4, 5]; numbers.forEach(function(number, index, array) { array[index] = number * 2; }); console.log(numbers); // Output: [2, 4, 6, 8, 10]
  • Explanation: In this case, the original array numbers is modified directly by doubling each of its elements using the array parameter within the callback function.

Use Cases:

  • Logging Values: Easily log each element of an array.
  • Modifying Data: Apply transformations or perform operations on array elements.
  • DOM Manipulation: Apply actions to a list of DOM elements (e.g., adding event listeners).
  • Aggregating Data: Summing, counting, or aggregating data across an array.

Important Notes:

  • forEach() is not chainable: Since it doesn’t return a new array, you can’t chain forEach() with other array methods like map(), filter(), etc.
  • Performance: forEach() is usually slower than a traditional for loop, but the difference is negligible for most use cases.
  • Immutable Arrays: If you need to create a new array based on the elements of an existing array, forEach() is not the best choice; consider using map() instead.