Search code snippets, questions, articles...

Array.forEach() in javascript

JavaScript's forEach method is one of several ways to loop through arrays. It can be used to perform a function on each element of an array. forEach is not just limited to arrays, it can also be used on other objects.
const myarray = ['1', '2', '3'];

myarray.forEach((item, index) => {
    console.log("item is : " + item + ", index is : " + index);
});
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

item is :  1 , index is :  0
item is :  2 , index is :  1
item is :  3 , index is :  2

Live Demo

Or you can write the above code in one line if you are using ES6

const myarray = ['1', '2', '3'];

myarray.forEach((item, index) => console.log("item is : " + item + ", index is : " + index));

If you are using ES5 you can use the below code to iterate over an array using the forEach() function

const myarray = ['1', '2', '3'];

myarray.forEach(function(item, index) {
    console.log("item is : " + item + ", index is : " + index);
});

The above code example is using the forEach() method to loop through the myarray array.

The forEach() method takes in a callback function that is invoked for each element in the array.

The callback function takes in two parameters, the first is the element in the array and the second is the index of that element.

The callback function then prints out to the console "item is :" followed by the element and ", index is :" followed by the index of the element.

# If you don't not need the index of the item in each iteration, then you can use the below code.

const fruits = ["Orange", "Apple", "Banana", "Pineapple"];

fruits.forEach( item => console.log(item) );

Output

Orange
Apple
Banana
Pineapple

Live Demo

Loop through array of objects using Array.forEach() function

The forEach() function allows you to iterate through an array and perform a function on each element of the array. This can be very useful for doing things like creating a list of items or performing a calculation on each element of an array.

Code example

const students = [
    { id: 1, name: "John", marks: 90 },
    { id: 2, name: "Sumesh", marks: 89 },
    { id: 3, name: "Rick", marks: 78 },
    { id: 3, name: "Monty", marks: 93 }
];

let total_marks = 0;

students.forEach(item => total_marks += item.marks);

console.log("Total Marks: " + total_marks);

Output

Total Marks: 350

This code example above is iterating over each object in the "students" array and adding the "marks" property of each object to the "total_marks" variable.

The "total_marks" variable is then logged to the console.

Was this helpful?
0 Comments