"How can it stop the loop?"
Like this:
// array callback
each([1,2,3,4,5], function(i, val) {
if (val === 3)
return false;
})
function each(array, callback) {
// iterate the collection
for (var i = 0; i < array.length; i++) {
// Invoke the callback, and store its return value
var result = callback(i, array[i]);
// If it returned `false`, break the loop
if (result === false) {
break;
}
}
}
What the value returned from a function is "meant" to do is ultimately up to the caller of that function.
In the above example, you pass the callback to the each()
function, and the each()
function calls it. Since the code in each()
is the caller, it gets to decide what to do in response to the value returned (if anything).