Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between for...in loop and jQuery each() function? [duplicate]

I am using the following scripts to iterate the object (I don't know which one is best to use, please tell me which one is the best):

var days = {Sunday: 0, Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6};

$.each(days, function(key, value){
    $('#days').append('<li>' + key + '(' + value + ')</li>');
});


for(var key in days){
    $('#days').append('<li>' + key + '(' + days[key] + ')</li>');
}
like image 915
Suresh Pattu Avatar asked Sep 14 '12 04:09

Suresh Pattu


People also ask

What is the difference between for loop and for of loop?

The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.

What is the difference between loop and function in Javascript?

Just as a loop is an embodiment of a piece of code we wish to have repeated, a function is an embodiment of a piece of code that we can run anytime just by calling it into action. A given loop construct, for instance could only be run once in its present location in the source code.

Which is faster each or for loop?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Can we use for loop in jQuery?

Looping through collections If you'd like to loop through multiple elements in a collection, you can use a normal for loop or jQuery's each() : $("p"). each(function(index, element) { $(element). text( $(element).


2 Answers

Either way, you should be caching that selector:

var elem = $( '#days' );
$.each(days,function(key,value){
    elem.append('<li>'+key+'('+value+')</li>');
});

.each() would be better in this case. The pattern is cleaner.

With a for loop, you'd want to use obj.hasOwnProperty(key) so that you don't dredge through inherited properties... Which adds another layer of indenting:

var elem = $( '#days' );
for( var key in days ){
  if( days.hasOwnProperty( key ) ){
    elem.append('<li>'+key+'('+days[key]+')</li>');
  }
}
like image 172
Matthew Blancarte Avatar answered Oct 04 '22 05:10

Matthew Blancarte


It is clear without any performance tests that native javascript for loop is faster, but there is no big difference for small arrays like 10-20 small items. So use whichever you want.

like image 40
Vahe Hovhannisyan Avatar answered Oct 04 '22 07:10

Vahe Hovhannisyan