const arr = [5,1,3,2,6];
const output = arr.reduce(function (acc, curr){
acc = acc + curr;
return acc;
}, 0);
console.log(output);
since there is return statement there, why the reduce function keeps iterating as return statement ends any loop or function as per my knowledge.
2
Answers
Yes, you’re right. However, you should also remember that
Array.reduce
is a function, which is different from the function you pass to it.When you call
Array.reduce
and pass in the function, it uses that function to do something. The return of the function does not also terminateArray.reduce
, untilArray.reduce
itself does areturn
or exits after it has finished doing whatever it does.The reduce function in JavaScript does not automatically stop its execution when a return statement is encountered. Instead, it iterates over each element of the array, applying the provided callback function to accumulate a single result. The return statement inside the callback function simply specifies the value to be used as the accumulator in the next iteration.
If you want to stop the execution consider using
break
or specify a condition in the reduce and return its value.Refer the below code for reference