JavaScript Array forEach
Method (Live Playground)
The JavaScript array forEach
method executes a provided function once for each array element.
Consider this basic example:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (item) {
console.log(item);
});
// Expected output:
// 1
// 2
// 3
// 4
// 5
In the example, numbers.forEach(function(item) { console.log(item); });
prints each number in the numbers array to the console.
Live Playground, Try it Yourself
The forEach
method also gives you access to the current index and the original array within its callback. Here's an example:
let numbers = [10, 20, 30, 40, 50];
numbers.forEach(function (item, index, array) {
console.log(`Item: ${item}, Index: ${index}, Array: ${array}`);
});
This will log the value, index, and original array for each iteration.
Live Playground, Try it Yourself
The forEach
method doesn't modify the original array, and it doesn't return a value. It's mainly used for side effects like logging to the console or pushing to an external array.
It's important to understand forEach
as it's a handy way to iterate through an array when you don't need to modify it.