1

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?

1 Answer 1

1

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 );
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.