JavaScript Array forEach() Method
The JavaScript Array forEach() method is a built-in function that executes a provided function once for each array element. It does not return a new array and does not modify the original array. It’s commonly used for iteration and performing actions on each array element.
Syntax
array.forEach(callback(element, index, arr), thisValue);
Parameters
This method accept five parameters as mentioned above and described below:
Parameter | Description |
---|---|
callback | It is a callback function executes on each array element. |
element | The current element being processed in the array. |
index (Optional) | The index of current element. The array indexing starts from 0. |
array (Optional) | The array on which forEach() is called. |
thisArg (Optional) | Value to use as this when executing the callback function. |
Return value
It does not return a new array. It returns undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function.
Example 1: Basic iteration to print array elements on console.
const arr = [1, 2, 3, 4, 5];
arr.forEach((item) => {
console.log(item);
});
Output
1 2 3 4 5
Example 2: Copy every element from one array to another array using Array.forEach() method.
// JavaScript Array forEach() Method
// Original array
const items = [12, 24, 36];
const copy = [];
items.forEach(function (item) {
copy.push(item);
});
console.log(copy);
Output
[ 12, 24, 36 ]
Example 3: Calculates the square of every element of the array using forEach() method.
// JavaScript Array forEach() Method
// Original array
const items = [1, 29, 47];
const squareOfItems = [];
items.forEach(function (item) {
squareOfItems.push(item * item);
});
console.log(squareOfItems);
Output
[ 1, 841, 2209 ]
Limitations of forEach() Method
- No Break or Continue: Unlike for loops, you cannot break the forEach() loop or use continue to skip to the next iteration. It will always iterate over all elements.
- No Return Value: The forEach() loop does not return a new array, it returns undefined.
- Asynchronous Issues: The forEach() loop does not handle asynchronous operations well. If you need to perform asynchronous operations, consider using for…of with async/await or Promise.all.