6

While digging into the source code of the underscore library, I found at that _.each relies on an ECMAScript 5 API Array.forEach whenever available:

var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
        obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
        for (var i = 0, l = obj.length; i < l; i++) {
            if (iterator.call(context, obj[i], i, obj) === breaker) {
                return;
            }
        }
    } else {
        for (var key in obj) {
            if (_.has(obj, key)) {
                if (iterator.call(context, obj[key], key, obj) === breaker) {
                    return;
                }
            }
        }
    }
};

I noticed that jQuery.each (the static one, not the .each method of a jQuery wrapper) does just a traditional for that calls the callback function, no matter if forEach is available or not. Is there a reason for that that I missed ?

4
  • 2
    jQuery is an object, not an array. You would have to convert back and forth between an array and the nodeList-like object to be able to chain the jQuery call to use the Array method. Commented Feb 22, 2013 at 4:57
  • @kennebec I'm talking about $.each(), not .each(). I edited the question to make it more clear. Commented Feb 22, 2013 at 5:18
  • One possible explanation is that jQuery's .each() doesn't have exactly the same interface as .forEach so the two are not interchangeable. If jQuery had their implementation first, then they'd have to break/change their API in order to use .forEach when present. Commented Feb 22, 2013 at 5:19
  • oops... sorry for the dupplicate Commented Feb 22, 2013 at 22:25

1 Answer 1

1

It's probably because the two differ in implementation - Array.forEach passes the array element as the first parameter, and the index as the second. jQuery.each passes the index first, the array element send.

Actually probably the best discussion source is right here on stack overflow:

jQuery.each implementation differs from native Array.forEach

Their guess being that it was a mistake - so many sites have implemented jQuery.each, expecting the index first, that they can't feasibly reverse them.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.