To iterate through an array’s items, the forEach() method can be helpful.
In this article, I’ll show how to use the forEach() array method to iterate items of an array in JavaScript.
array.forEach() method calls a function and iterates over the array items in ascending order without mutating the array.
The syntax of the forEach() method is:
array.forEach(function(currentValue, index, arr));
Example: We display each element of an array.
With for-loop
let names = ["Anna", "John", "Peter"];
// using for-loop
for(let i = 0; i < names.length; i++) {
console.log(names[i]);
}
With forEach
let names = ["Anna", "John", "Peter"];
// using forEach
names.forEach(function(name) {
console.log(name);
});
Output
Anna
John
Peter
We can use the arrow function with the forEach() method.
let names = ["Anna", "John", "Peter"];
// using forEach
names.forEach(name => {
console.log(name);
});
We can use the forEach() method to update the array elements.
let names = ["Anna", "John", "Peter"];
// using forEach
names.forEach(function(item, index, arr) {
arr[index] = 'Hello ' + item;
});
console.log(names); // ["Hello Anna", "Hello John", "Hello Peter"]