Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Recursion function in JavaScript

I have a simple recursion function that returns the sum of the first n elements of the array. I'm a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1]; what actually this sum(arr, n-1) does as it is not added to the final sum eventually and why it's not been calculated.

Here's the whole function, really appreciate any explanation.

function sum(arr, n) {
  if (n === 0) {
    return 0;
  } else if (n >= 1) {
    return sum(arr, n - 1) + arr[n - 1];
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In a recursive function, you want to start with the leaving return statement, which in this case is when the array is empty.

// if the array is empty, return the total.
if(!arr.length) return total;

If we have more items, pop the top item and add it to the total. Popping returns the last item and removes it from the array.

total += arr.pop();

Then we return the recalled function and pass it the updated parameters.

return sum(arr, total);

function sum(arr = [], total = 0) {
  if (!arr.length) return total;
  total += arr.pop();
  return sum(arr, total);
}

console.log(sum([1, 2, 3]))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!