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?
returnexists 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 objis an expression that will return true if and only ifobj(or a chained [[prototype]]) has the propertyprop(with any value, includingundefined). In this case note the values ofiare over the range[0, length). The result here is “for each assigned index in an array”.iteratorevaluates to a function and is invoked withcall()so the context (thiscan be set). The specialbreakervariable evaluates to a special sentinel object. For objects,===is an “identity equal” and no other new object will===the object assigned tobreaker.In short: it is a variant of
Array.forEach(ECMAScript ed. 5) orjQuery.each(the utility method) that iterates over a sparse array, passes some additional arguments and allows “early termination”.Happy coding.