HomeAbout MeContact

forEach() Method in javascript and how to use it .

By Gopal Baskota
Published in JavaScript
January 04, 2021
1 min read

forEach() method will loops through an array and runs a callback function for each value in the array and then returns undefined .

let arr = [a,b,c];

arr.forEach((value, index, array)=>{
  console.log(value);
});

// 1
// 2
// 3
// undefined

Note: forEach() will always returns undefined .

using forEach() in a function .

const countA = (arr) =>{
  let total = 0;
  arr.forEach(function(val){
    if(val === 'a') {
        total++;
    }
  });
  return total;
}

countA(['a','b','c','a']); // 2
countA(['b','b','c','a']); // 1
countA(['c','b','c','d']); // 0

Tags

javascriptforEach
Previous Article
How to write an function that accept an array and return a new array with values doubled.

Gopal Baskota

Full stack Web Developer

Topics

JavaScript
NodeJs
React Js

Related Posts

javascript algorithms - Insertion sort Explained using Javascript .
January 11, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media