Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.each([collection]) vs $([collection]).each()

Both methods appear to produce the same results, but I've been hard-pressed to actually convince people that the second method works, since it's apparently not commonly known.

// Create some data
var foo = { 'vals':[ {'id':'foo'}, {'id':'bar'} ] }​​​​​​​​​​​​​​​​​;

// Common Method    
$.each(foo.vals, function(i,o){
    alert(this.id);
});

// Alternative (lesser-known?) Method
$(foo.vals).each(function(i,o){
   alert(this.id); 
});

Upon checking the source, these two appear to be one-in-the-same. The second method follows:

each: function( callback, args ) {
  return jQuery.each( this, callback, args );
}

This method demonstrably calls the more commonly-known method, meaning it's just as legitimate. Is this understanding correct, or am I missing something here?

I have typically trusted this method since it didn't cause me to deviate from standard practices with regards to selectors. Let's face it, we're trained to do:

$("p").each();

So it seems only natural to do:

$(obj).each();

Am I mistaken?

like image 833
Sampson Avatar asked Feb 23 '10 20:02

Sampson


1 Answers

The difference between the two is actually exponential depending on how you are using it.

The first $.each constitutes a single function call to start the iterator.

The second $(foo.vals).each makes three function calls to start the iterator. The first is to the $() which produces a new jQuery wrapper set (Not sure how many other function calls are made during this process). Then the call to $().each. And finally it makes the internal call to jQuery.each to start the iterator.

In your example, the difference would be negligible to say the least. However, in a nested use scenario, you might find performance becoming an issue.

Finally, Cody Lindley in jQuery Enlightenment does not recommend using $.each for iterations greater than 1000 because of the function calls involved. Use a normal for( var i = 0... loop.

like image 57
Doug Neiner Avatar answered Sep 29 '22 15:09

Doug Neiner