When going through the underscore.js library, i came across
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
// Establish the object that gets returned to break out of a loop iteration.
breaker = {};
why is return used at the end? and what does i in obj check?
return exists the function (with the specified return value, if any). This will be covered in a tutorial. In a looping construct it "stops early".
prop in obj is an expression that will return true if and only if obj (or a chained [[prototype]]) has the property prop (with any value, including undefined). In this case note the values of i are over the range [0, length). The result here is "for each assigned index in an array".
iterator evaluates to a function and is invoked with call() so the context (this can be set). The special breaker variable evaluates to a special sentinel object. For objects, === is an "identity equal" and no other new object will === the object assigned to breaker.
In short: it is a variant of Array.forEach (ECMAScript ed. 5) or jQuery.each (the utility method) that iterates over a sparse array, passes some additional arguments and allows "early termination".
Happy coding.
It seems like that code loops over some iterator object and breaks when a breaker variable has been reached. The return statement exits the function.
Note that breaker is not something you can use yourself to break out of a _.each loop; it's only accessible inside underscore itself and is used internally by the _.all and _.some methods.