Doug Smith Doug Smith - 28 days ago 8
Javascript Question

How many Returns with every() and other iterative methods?

This is a general question for some of Javascripts array methods. Take the following as an example:

var numbers = new Array(12, 5, 8, 130, 44);

function isBigEnough(element, index, array) {
return element >= 10;
}

alert(numbers.every(isBigEnough));


This will return FALSE.
When I first read about these methods (such as every, some, filter, forEach, map) that iterate over an array, I thought that the function isBigEnough would be called for each element. So in the above example, I would have thought that isBigEnough would be called five separate times with 5 return values. Clearly this is not that case.

I'd now guess that the method calls the function 5 times, but the Return doesn't actually return anything until either all elements are TRUE, or until a FALSE is found.

Does anyone know of a flowchart or graphic that shows the process or flow of these iterative methods?

thanks

Answer Source

Mozilla documentation for these methods is very good. For every and some it specifically states that the methods return immediately on finding a falsy/truthy value.

every

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

some

some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some