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

276
Vistas
Whats going on here im trying to wrap my head around recursion and this return function

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

So far I understand that by me setting countArray to the function it decides to call itself until n = 0 . At that point it returns an empty array to countArray but i just don't understand what happens after that point that gives this odd outcome of the numbers being ordered, i assumed it would just push the current value of N being 0 to the array but it clearly doesn't...

Does anyone know what's going on here?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

0 is not pushed to the array because of the if condition. At that point your countArray is set to [].

When using recursion interpreter needs a way to be able to understand in which order these functions have to be processed.

When your script runs first time, the interpreter creates a global execution context and pushes it to the execution stack.

Once it finishes, the engine executes the function whose execution context is at the top of the stack first. In your case n=1. It pushes it to the array, pops it from the stack then continues n=2 and so on until it reaches the last one in the stack n=5

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    console.log(n)
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

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