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

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

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 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