skip to Main Content
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


  1. 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 terminate Array.reduce, until Array.reduce itself does a return or exits after it has finished doing whatever it does.

    Login or Signup to reply.
  2. 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

       
    
    const arr = [5, 1, 3, 2, 6];
    const condition = 10;
    let output = 0;
    
    for (let i = 0; i < arr.length; i++) {
        output += arr[i];
    
        if (output >= condition) {
            break; // exit the loop when the condition is met
        }
    }
    
    console.log(output);  // Output will be 9 (5 + 1 + 3)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search