Jacob Stamm Jacob Stamm - 1 year ago 101
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

function like this:

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

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

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

Obligatory but unnecessary JSFiddle

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

Answer Source

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 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download