Why can't I break out of a reduce
in Javascript?
Seems a simple return
or even a throw
will not break it at all. Exactly why does it need to loop through all of the values?
Why can't I break out of a reduce
in Javascript?
Seems a simple return
or even a throw
will not break it at all. Exactly why does it need to loop through all of the values?
Because that's what it's designed to do - it will always loop through all items in the array, just like most other array methods like forEach
and map
.
If, past some point, you want to effectively ignore what comes afterwards, just return the current accumulator, for example:
const partialSum = [1, 2, 3, 4].reduce((a, num) => {
if (a > 3) {
return a;
}
return a + num;
}, 0);
console.log(partialSum);
If you want to find an element in the array instead, you should use .find
, which will terminate the loop as soon as a match is found:
const arr = [
{ prop: 'foo' },
{ prop: 'bar' },
{ prop: 'baz' }
];
const foundBar = arr.find((obj) => {
console.log('iteration');
return obj.prop === 'bar';
});
A throw
will indeed break out of a .reduce
(although you shouldn't use errors for control flow):
[1, 2, 3, 4, 5].reduce((a, num) => {
console.log('iteration');
if (num > 2) {
throw new Error();
}
});
If your codebase seems to frequently need breaking inside of a reduce
, it might be a better idea to use a for
loop instead. However, if you absolutely have to use reduce
and need to break from inside of it, you can use one of the following options:
throw
to break out of the reduce
method, although this is not recommended.4th
argument of the reducer function, which is the array being iterated over. If you mutate it to an empty array, reduce
will exit. Be careful with this, as it can have unwanted side effects.reduce
is designed to iterate over all of the elements in an array, therefore this is why it's not easy, common or recommended to break out of it. This is also why there are so many other array manipulation methods, as reduce
can in theory replace all of them given the proper function, however it presents certain limitations that other array methods do not.