Jacob Stamm Jacob Stamm - 2 months ago 9
jQuery Question

Difference between $(array).each(...) and $.each(array, ...) in jQuery

If I have an array in a JavaScript variable that I want to iterate through, I usually use jQuery's

.each()
function like this:

var myArray = ["foo", "bar"];
$(myArray).each(function(index, value) {
console.log(value);
});


But I can achieve the same effect by passing in my array as an argument to the
.each()
function, like this:

var myArray = ["foo", "bar"];
$.each(myArray, function(index, value) {
console.log(value);
});


Obligatory but unnecessary JSFiddle

This question can apply to basically any other jQuery function as well, not just
.each()
. Is there a functional difference between these two different usages?

Answer

No, there is no difference in the way they function.

The main difference is going to be that using $.each() allows you to pass in an array whereas using $().each() requires you to have a constructed jQuery object to use as the context.

There is a slight difference in readability, but that is negligible.

If you were to look at jQuery's source code, you could also confirm this, as $.each is simply just a call to prototype's definition of each:

// Execute a callback for every element in the matched set.
each: function( callback ) {
    return jQuery.each( this, callback );
},