Asked 8 years ago
18 Nov 2016
Views 1086
sarah

sarah posted

differnce between forEach and each in JavaScript ?

differnce between forEach and each in JavaScript ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

first of all forEach is like for loop . its used for looping in array. and each used for to iterate objects array wont work with simple array

var criteria = ['manufacturer','storage','os','camera'];
criteria.forEach(function(item,key){
alert(item);
})

will give you alert for all criteria one by one

var criteria = ['manufacturer','storage','os','camera'];
criteria.each(function(item,key){
alert(item);
})

wont work because each dont work with array
but if use like this , it will work

 var div = $('div');
div.each(function () {
 alert(this);
 
      });


.each function is jQuery function and forEach is available without any framework its core JavaScript function

so if you want to use .each you need to include jquery first

<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

forEach dont need anything to include to work it .
Post Answer