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

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

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

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

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