Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda