trying to understand underscore.js

Go To StackoverFlow.com

2

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?

2012-04-04 02:47
by Lordking
What function is that in? Perhaps a link to the source - Jakub Hampl 2012-04-04 02:52
Julian Bucknall (CTO of Developer's Express) just recently ran a series of blog posts about understanding underscore.js. I don't have a URL handy, but perhaps you can find a reference to the posts at http://devex.com or via an internet eearch. I'll try and find the link tomorrow and update this comment if you haven't found an answer by then - Ken White 2012-04-04 02:54


3

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.

2012-04-04 03:01
by NoName
+1 for actually taking apart the expression - Blender 2012-04-04 05:34


1

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.

2012-04-04 02:50
by Blender


1

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.

2013-01-08 00:59
by Andrew Magee
Ads