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

245
Vistas
WHy in my recursion function the code after the if condition is repeated?
// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
    countDown(newNumber);
  }
  console.log(newNumber);
}

countDown(4); 

// output => 4 3 2 1 0 1 2 3

I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).

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

0

Your recursive call does not end the execution of the function.

So what happens is that if you call newNumber(2) it executes the first console.log, logging 2. Then it assigns newNumber to 1. Then your recursion happens, printing 1. Inside the recursive call newNumber becomes 0, so no more recursion. Instead, the second print inside the recursion prints 0. Now your recursion returns, and the second print outside of your recursion prints the current value of newNumber in the non recursive call. And that is 1.

So you get 2 (outside recursion) 1 (inside) 0 (inside) 1 (outside)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can simplify your function.

function countDown(number) {

  if (number > 0) {
    console.log(number);
    countDown(--number);
  }

}

countDown(4);

about 4 years ago · Juan Pablo Isaza Denunciar

0

this way ?

countDown( 4 )

// program to count down numbers to 1
function countDown(num)
  {
  if (num<1) return
  console.log(num)
  countDown(--num)
  }

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