I was examining how UnderscoreJS implements their each
/forEach
//somewhere up top:
var breaker = {};
//then the each function
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;
}
}
}
};
//iterator = callback
//context = optional third parameter of each to provide context in the callback
//obj = the list
//key = key of the object (i for index when an array)
Basically, it's executing the callback for each item in the object/array. But this like confuses me
if (iterator.call(context, obj[key], key, obj) === breaker) return;
From what I understand, if the callback returns an object, the loop breaks, but... Why it's comparing to breaker
which is an internal object in the underscore module?. Doesn't it evaluate to false
all the time since, even if the callback does return an object, it is always false
since it's not the same object (therefore the loop never breaks). What's the reason behind this?
Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.
The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering.
Underscore. js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: https://underscorejs.org.
They use each
internally for e.g. some
. Since some
does short-circuit, they can have each
break there using the "secret" object, while not exposing this feature for regular users. They don't expose the break feature because the native function doesn't do that, either (so their shim is as native-like as possible). If they did, the break feature would only be available if the native function is unavailble, which isn't particularly helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With