forEach Method in Java Script
In JavaScript, the forEach method is used to iterate over elements of an array and execute a provided function once for each array element. It's a clean and readable way to loop through array elements.
Syntax
array.forEach(callback(currentValue, index, array), thisArg);
Parameters
callback: A function that gets executed for each array element.
It takes three arguments:
currentValue: The current element being processed.index (optional): The index of the current element.array (optional): The array forEach is iterating over.
thisArg (optional): A value to use as this when executing the callback.
callback: A function that gets executed for each array element. It takes three arguments:
currentValue: The current element being processed.index(optional): The index of the current element.array(optional): The arrayforEachis iterating over.
thisArg (optional): A value to use as
thiswhen executing the callback.
Example 1: Basic Iteration
const numbers = [1, 2, 3, 4];
numbers.forEach((num) => { console.log(num);});// Output:// 1// 2// 3// 4
Example 2: Using Index
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`); }); // Output: // 0: apple // 1: banana // 2: cherry
Notes
- Does not return a value: Unlike
map, forEach does not
create a new array but operates on the original array. - Cannot be stopped: You cannot use
break or continue in a forEach loop.
If you need to break out of a loop, consider using a traditional for
loop or a for...of loop.
- Does not return a value: Unlike
map,forEachdoes not create a new array but operates on the original array. - Cannot be stopped: You cannot use
breakorcontinuein aforEachloop. If you need to break out of a loop, consider using a traditionalforloop or afor...ofloop.