Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!