Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would jquery's .each() callback have the indexInArray as the first argument instead of valueOfElement?

A strange question, but every time I use jQuery.each() I wonder why the indexInArray is the first argument and not the second (the second currently being the value itself), like the native array.forEach()?

There is an identical, but unanswered question with a decent number of upvotes on the API docs for .each() too!

More often than not, I find code that "acts on" the value and not the index, resulting in an unused variable in the body of the function (which makes js(h|l)int complain, with good reason in my opinion). So, why isn't the value the first argument?

Is this a hangover from an poorly thought out implementation in an earlier version, or is there a good reason for this?

like image 742
BenLanc Avatar asked Jan 30 '26 20:01

BenLanc


1 Answers

The reason is that the first argument of foreach, the value, is less needed in $.each as jQuery provides it as this.

Thus, the index appears to be more often useful. This is a good reason.

I write "appears", because this doesn't come without perils : this isn't exactly the same as the value when the value is of primitive type : in this case the value is wrapped as an object.

Why is it dangerous ?

Here's why :

[1, 2, 3].forEach(function(v) {
    if (v===2) console.log('found!');
});

Output in the console :

found!

Now with jQuery :

$.each([1, 2, 3], function() {
    if (this===2) console.log('found!');
});

What’s the output ?

Nothing.

(note that I detail the implementation leading to this in this related question.)

Today, with people being more and more used to the standard javascript function, it might be thought that having the other order would have been better (that was the choice of Underscore.js). The reason to provide the index first was good, but maybe not good enough. But maybe it doesn't really matter as we probably won't continue using $.each now that foreach is generally available (at least for arrays).

like image 56
Denys Séguret Avatar answered Feb 01 '26 15:02

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!