For Each
two primary methods exites for iterating though array element in javascript.
1. loops
2. forEach() Medthods
why we use these methods to iterate arrays . already we are using For loop to iterate aarry.
using loops we have so many disadvantages (or) problems
- we have to use more variables
- if we want to bind a data too every function ForLoop won't wok properly
- when we are doning unit testing or in maintainance , using forEach method is better to iterate arrys.
ForEach() : the forEach() method calls a function (a callback function) once forEach array element
var arr= ["arr1","arr2","arr3"];
arr.forEach(function(arr4)
{
alert(arr4)
})
Note :Here, callback function inside the forEach , it will call every element of array
, when ever call that respective element it will pass that element as argument
Ex:
var ar = [12,10,32,25,54,65];
ar.forEach(function(x,ind){
console.log("lets go",x,ind)
})
Note : every time function is calling and sending that particular number to that argument x .
particular element pass as first argument,index will pass as second arugument