How to use forEach loop over Arrays in Javascript?
I'm stuck on JavaScript basics, forEach looping over arrays. Can anyone explain me?
1 Answer
5 years ago by Jahaan
forEach method is used to run a function on every element present in an array. This method can only be used on Arrays, Maps and Sets.
You can either use callback functions or Arrow functions in forEach method.
Remember that you can not break, return or continue in forEach method like you do in traditional for loop. If you want to do so, then use exceptions in the call back function.
forEach Syntax
arrayname.forEach(function(err,doc){
//code
});
Example1 : Using Callback function
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = [];
numbers.forEach(function(ele){
if(ele % 2 == 0)
squaresOfEvenNumbers.push(ele*ele)
});
console.log(squaresOfEvenNumbers);
click here for results.
Example2 : Using Arrow function
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = [];
numbers.forEach( ele => {if(ele % 2 == 0)
squaresOfEvenNumbers.push(ele*ele)})
console.log(squaresOfEvenNumbers);
click here for results.
5 years ago by Divya