views:

255

answers:

2

Hi,

I have noticed there is a difference in parameter orders between callback function of .each() and .grep() functions in jquery.

jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] )

jQuery.each( collection, callback(indexInArray, valueOfElement) )

Do you have any idea of the possible reasons that they preferred to have indexInArray as the 1st parameter in .each() and as the 2nd in the .grep() function?

Thanks, burak ozdogan

A: 

I don't know whether there is a real answer for this or not but lets have a look at the usage of the function:

  • In .grep, an element of an array is processed. The index of this element is not necessary to process the element. It is more or less optional and therefore the second parameter.

  • In .each, no parameter is really necessary. But as the element can be accessed via this inside the function, it makes sense that the element is set as second parameter. This way, one doesn't have to specify two variables only to use the index.
    If the parameters were in reverse order and you want to use the index, you would have to specify a variable for the element and you might not be able to use this anymore (but I am not sure about that).

So in the end it is a matter of convenience.

Felix Kling
A: 

Well, one might say that the arguments have the same order. If you look at the source code, you will see that in grep, the callback is called like this:

callback( elems[ i ], i ) )

whereas in each (when dealing with an array and not a map):

var value = object[0];
callback.call( value, i, value )

where value is the this object. This way of calling a method is used in order to override the value of this.

So I guess, the preferred way of using each is to use this in order to refer to the object.

In my opinion this difference isn't a good thing as it makes the life of the users harder. I've checked and both versions were introduced at 1.0 version, so it can't be justified that this was caused by two different opinions.

kgiannakakis