The forEach() method in JavaScript is used to iterate over an array and execute a function for each element without creating a new array. It is a simpler and more concise way to perform a loop compared to using a traditional for loop.
Syntax
array.forEach(callback(currentValue, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback | A function to execute on each element in the array. It takes three arguments: |
currentValue | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array forEach() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
undefined | There is no explicit return value. |
Example 1: Using forEach() to Log Array Elements
This code demonstrates how to use the forEach() method to log each element of an array to the console.
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(function(number) { console.log(number); }); // Output: // 1 // 2 // 3 // 4 // 5
Example 2: Using forEach() with Arrow Function
You can use an arrow function for a more concise syntax.
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(number => console.log(number)); // Output: // 1 // 2 // 3 // 4 // 5
Example 3: Using forEach() to Update Array Elements
You can also use forEach() to update array elements in-place.
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]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |