When we have an array of data we often required to loop through all the array elements and perform some action using the array elements. We can do this using for loop, but JavaScript array forEach() method is the new way to do it.

How forEach() method works

The JavaScript array forEach() method iterates over the array elements and executes a function for each element. Syntax is:

array.forEach(callback, thisArg);

The callback is a function that executes for every array elements and thisArg is a value to use as this in callback.

Example:

let foods = ['bread', 'rice', 'meat', 'pizza'];

foods.forEach(function(food) {
    console.log(food);
});

Output

bread
rice
meat
pizza

#web-development #javascript #javascript-tips #arrays

JavaScript Array forEach() method to loop through an Array
3.25 GEEK