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

184
Views
Recursion Explained

Produce the sum of the first n values in an array.

function sum(arr, n) {
  
  if (n <= 0 ){
    return 0;
  } else { 
    return sum(arr, n-1) + arr[n-1];
  }
 }

Hello, I have this simple recursive function from freecodecamp. I understand the concept of recursion, however I can't seem to wrap my brain around why this works in this exact use case.

I am mainly struggling to understand how the count is being increased and stored to produce a final total sum, as well as why the function doesn't return 0 as the sum once it hits its breakpoint.

Any explanations are appreciated, thank you.

Also this is not for a project or anything of the sorts, just trying to understand this concept better.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Think of each recursive call as adding a frame on the stack. All the called frames have to give answer before you can compute answer for current frame.

Caller program starts:

FRAME_A
sum([5,7,10],3)
n <= 0: False
answer here = sum([5,7,10],2) + 10
              ^
             wait for this to be computed
             let's call this WAIT_A

--------
FRAME_B
sum([5,7,10],2)
n <= 0: False
answer here = sum([5,7,10],1) + 7
                ^
                wait for this to be computed
                let's call this WAIT_B

---------
FRAME_C
sum([5,7,10],1)
n <= 0: False
answer here = sum([5,7,10],0) + 5
                ^
                wait for this to be computed
                let's call this WAIT_C
---------
FRAME_D
sum([5,7,10],0)
n <= 0: True
return 0
FRAME_D is done.
(Now, we are rolling back)

WAIT_C is now 0. FRAME_C answer is 0 + 5 = 5. FRAME_C is done.
WAIT_B is now 5. FRAME_B answer is 5 + 7 = 12. FRAME_B is done.
WAIT_A is now 12. FRAME_A answer is 12 + 10 = 22. FRAME_A is done.
All frames are done. Final answer = 22.
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!