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 ?

Samuel Rossille
  • 18,940
  • 18
  • 62
  • 90
  • 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. – kennebec Feb 22 '13 at 04:57
  • @kennebec I'm talking about $.each(), not .each(). I edited the question to make it more clear. – Samuel Rossille Feb 22 '13 at 05: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. – jfriend00 Feb 22 '13 at 05:19
  • oops... sorry for the dupplicate – Samuel Rossille Feb 22 '13 at 22:25

1 Answers1

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.

Community
  • 1
  • 1
chug187
  • 138
  • 1
  • 2
  • 8