Home > Mobile >  Recursion in JavaScript question- how is the position of console.log here affecting the order in whi
Recursion in JavaScript question- how is the position of console.log here affecting the order in whi

Time:11-09

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?

CodePudding user response:

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