Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does reduce in JavaScript/ECMAScript 5 stop on first false when using with and operator?

var a = [7,8,9,4,5,3,2,0,44];
[0,2,8].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true

[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//false

[0,2,8,44].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true

Works fine!

Is it smart enough to stop when callback fn returns false the first time ?

BTW that code checks if array 'a' contains everything array 'arr' contains .

like image 958
Amogh Talpallikar Avatar asked May 23 '26 17:05

Amogh Talpallikar


2 Answers

Is it smart enough to stop when callback fn returns false the first time ?

No. The return value of the callback just becomes the value of its first parameter in the next iteration.

For example, in this call:

[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)

In each iteration, these are the values of p, c, and i (arr is always [0,2,8,45]):

p     c  i  return
true  0  0  true
true  2  1  true
true  8  2  true
true 45  3  false

The last return value is the final return value of reduce. It will always iterate over all values in the array.

~~~~~~~~~~~~~~~~~~~~~~~~~~

If you want something that stops on the first false, use every:

[0,45,2].every(function(c,i){return a.indexOf(c)>-1 }) // false. Stops on 45
like image 125
Matt Avatar answered May 26 '26 08:05

Matt


No.
The reduce() function doesn't know what your callback does; it has no idea it's always short-circuiting.

Call every() instead.

like image 29
SLaks Avatar answered May 26 '26 07:05

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!