0

Possible Duplicate:
underscore's each checking for {} return of callback

I was taking a look at underscore's source and implementation of the Foreach method. I just have one question with the below method.

var breaker = {};

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 (i in obj && 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 am struggling with the following line? Why check if the iterator being called is an empty object? Why would you return an empty object from the iterator?

if (iterator.call(context, obj[key], key, obj) === breaker) return;
Community
  • 1
  • 1
TYRONEMICHAEL
  • 4,174
  • 4
  • 30
  • 47
  • To abort the iteration (e.g. the `any` predicate, if you found something matching the condition, you don't need to go any further). – DCoder Sep 16 '12 at 06:11
  • Could you perhaps provide an example of the Foreach being aborted. You can post it as answer, and I will mark it as correct. I am struggling to find out where breaker is being set in the library. All I can see in the source is that its being declared as an empty object. I also found this [link](http://stackoverflow.com/questions/8779799/how-to-break-the-each-function-in-underscore-js), which states that with the foreach you cannot break out of the loop. – TYRONEMICHAEL Sep 16 '12 at 06:20
  • 3
    I started writing an answer, but then I noticed [this question](http://stackoverflow.com/questions/11600735) - I think that answer will be sufficient. – DCoder Sep 16 '12 at 06:32

0 Answers0