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

134
Vistas
Return Statement is not doing what I would have expected

Here is the code.

print(5);

function print(n) {
  if (n == 0) {
    return;
  }
  print(n - 1); //call function recursively  
  console.log(n);
}

I would expect after the return statement that console.log(n) would output zero (0)because that was the value of n when I called the return statement. Instead it returns 1 - 5 ??? Return was only called once, so can anyone explain what is going on here?

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

0

Within your code there is an implicit return, think of the function more like this:

function print(n){
    if(n==0){
      return ;
    }  
    print(n-1); //call function recursively  
    console.log(n);
    return undefined;
  }
   

So when print(n-1) is called with 4 it'll recurse down until you get to you're value of 0. After that however, the calling function will log the n value.

Essentially your return only returns to the caller, it doesn't completely unwind the callstack and prevent that console.log being called. It'll look something like this:

print(n-1); // called with 4
  print(n-1); // called with 3
    print(n-1); // called with 2
      print(n-1); // called with 1
        print(n-1); // called with 0
        return;
      console.log(n) // 1 
    console.log(n) // 2
  console.log(n) // 3
console.log(n) // 4
console.log(n) // 5
about 4 years ago · Juan Pablo Isaza Denunciar

0

The print function is still called five times. The value of n does not propagate to the earlier calls.

The return statement does not end the whole chain of recursive calls. Execution proceeds after the return statement in the line where the exiting function was called.

If you want some code to be executed only once in a recursive function, put it before the return in the if branch:

function print(n) {
  if (n == 0) {
    console.log(n);
    return;
  }
  print(n - 1); //call function recursively  
}
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