What is the importance of breaker in underscore.js? [duplicate]

梦想的初衷 提交于 2019-12-05 12:07:01

From the Annotated source code,

Establish the object that gets returned to break out of a loop iteration.

It is just a sentinel value and if the iterator function returns breaker, _.each will return immediately. Since, breaker is not assigned to any other object, no other object can be equal to breaker (it is matched with ===). It is used internally, by _.every and _.any.

_.every

if (!(result = result && iterator.call(context, value, index, list))) return breaker;

_.any

if (result || (result = iterator.call(context, value, index, list))) return breaker;

These two functions return breaker, so that _.each will break out of the iterations.

It is used in other _underscore helpers, like _.all(), _.every(), _.any() which use the _.each() function to loop through the collection, but return the breaker when they wanna stop the each loop (i.e. they found the element they were looking for etc.)

If you scroll up in the code, you will see the following code:

var breaker = {};

So it is checking if the function it is calling (the iterator) is returning an empty object. If it is, the each "loop" is broken and the function ends.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!