Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda