views:

61

answers:

2

In jQuery, what's the difference between the following two constructions of jQuery.each:

// Given
var arr = [1,2,3,4],
    results = [],
    foo = function (index, element) { 
       /* something done to/with each element */
       results.push(element * element); // arbitrary thing.
    }

// construction #1
$.each(arr, foo); // results = [1,4,9,16]

// construction #2
$(arr).each(foo); // results = [1,4,9,16]

Is there any difference, or is it purely syntax?

+8  A: 

The $().each() is just a wrapper for $.each(), you can see this in the core code:

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

Though, $(something).each() is intended for elements, I can't promise you using it with a plain array won't break later (it's unlikely it'll break, since jQuery objects are wrapped arrays though). The intended use is directly calling $.each() in this case.

Nick Craver
+1  A: 

Theres no difference with the way the array is handled but purely syntax.

jQuery is very loose library and and allows you to take advantage of each function differently to suite you.

jQuery handles the this like so

function each(first,second)
{
    array = (instanceOf this == Array) ? this : ((first instanceOf Array) ? first : second);
    callback = (instanceOf second == Function) ? second : first;
    //As  you can see its testing what types are being sent to the fintion
}

if the first argument is an function then this Must be the array I.E $([1,2,3,4]).each(callback) otherwise its expected that first is the array and second is the callback IE `$.each(array,callback);

but either way the process is pretty much the same`just the argument type checking helps a user be lose about how to handle the situation.

Even tho this is not the way each is actually handled there's a few functions that use this technique to create the looseness

RobertPitt
These are 2 different functions, one on jQuery itself, one a method available on jQuery objects... It's not like `.fadeIn(callback)` and `.fadeIn('slow', callback)`, that's a different overload concept that you're describing, it's all about optional parameters.
Nick Craver