forEach method

The forEeach method in JavaScript is an array method used to execute a provided function once for each element in an array. It’s beneficial when you want to perform side effects such as logging, updating each element in place, or calling functions that do not require returning a new array.

Syntax:


array.forEach(function(element, index, array) {
  // Your code here
}, thisArg);

element: 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.

Characteristics of forEach

1. Does Not Return a Value: The forEach method always returns undefined. It doesn’t return a new array, unlike some other array methods like map.

2. Iterates Over Every Element: The function passed to forEach is executed for every element of the array, even if it is undefined, null, or an empty slot.

3. Cannot Be Interrupted: You cannot break out of a forEach loop using break or continue. If you need to stop iteration based on a condition, consider using a for loop or the some or every methods.

4. Modifying the Array: You can modify the original array within the forEach loop by directly altering its elements.

Example: Modify the array element


const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
    arr[index] = num * 5; // multiply by 5 for each element in the original array
});
console.log(numbers); // Output: [5, 10, 15, 20]