forEach() method|Javascript Explained!

Photo by JJ Ying on Unsplash

forEach() method|Javascript Explained!

Let's say we want to perform some task or play with the individual elements of an array, then how we should approach it? We know the methods like push(),pop() which help us to manipulate the array but we can't perform a function on individual values of the array. For that, we have forEach() array method which comes into action

What is forEach() method

forEach() method calls a specific function on each element of an array at least once.

Syntax

array.forEach(function(currentItem,index,arr))

Let's break the above forEach() method syntax

callback function-> function to be executed on each item of an array.

(callback function: function that is passed to another function as a parameter is called callback function)

currentItem ->current element which is being processed.

index-> index of a current item in the array.

arr-> array on which forEach() is called upon ,this is rarely used parameter.

Now,let's see forEach() in the working

const fruits=["banana","grapes","kiwi","orange","mango"];

 fruits.forEach(Item);

function Item(item)
{
  console.log(item);
}

console1.png

We can do a lot with the forEach() method. Solve the below question to have a good grasp of the topic.

Q.Find the sum of the values of an array?

const arr=[5,10,15,20,25,30,35];
let sum=0;

 arr.forEach(item=>{
     sum+=item;
 });
console.log(sum);

we have used the arrow function above and wrote an inline function.

console2.png

NOTE: The Array.forEach method is supported in all browsers expect IE version 8 or earlier:

HAPPY CODING!