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

144
Visualizações
Recursion in JavaScript question- how is the position of console.log here affecting the order in which values are returned?

I'm fairly new to programming and I'm learning about basic recursion for the first time. A result I just got playing around with a practice question in JavaScript is really baking my noodle.

function countDownRecursive(n) {
   if (n == 0) {
     console.log('Hooray!')
     return
     } else {
       console.log(n)
       countDownRecursive(n-1)
       console.log(n)               
     }
}

The output of ie, countDownRecursive(3) is

3 2 1 Hooray! 1 2 3

My question is why does putting console.log() after countDownRecursive(n-1) like this cause JS to log the values in reverse?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

On the initial call, the else is entered, and

   console.log(n)
   countDownRecursive(n-1)

3 is logged. Then, the initial countDownRecursive(3) function being suspended while countDownRecursive(3-1) is called. The stack is now composed of countDownRecursive(3).

The same thing happens with countDownRecursive(2). 2 is logged, and with its recursive call, the stack is now composed of countDownRecursive(2) and countDownRecursive(3).

And so on. At the end, with countDownRecursive(0), the stack is

countDownRecursive(0) <-- current function
countDownRecursive(1)
countDownRecursive(2)
countDownRecursive(3)

and 3 2 1 has been logged.

At 0, there's no more recursion, so there's Hooray. That innermost countDownRecursive(0) ends, and then the countDownRecursive(1) resumes at the point at the point of the recursive call:

   countDownRecursive(1-1) // this line just finished
   console.log(1)    

so 1 gets logged, and that function ends.

The functions keep resuming, logging, and exiting, until the stack is empty, and you're left with logs of

3
2
1
Hooray!
1
2
3
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