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

140
Views
Why does this recursive function count down as well as up?

It's counter-intuitive why this recursive function counts down as well as up. Can anyone explain it?

function counter(value, limit) {
    if (value === limit) {
        console.log(value);
    } else {
        console.log('going up:', value); // on the way down / going deeper (increment)
        counter(value + 1, limit);
        console.log('going down:', value); // on the way up / coming up from the depths (decrement)
    }
}
counter(0, 3);

Addendum

I notice when I add a setTimeOut(), it outputs the pre- and post-values together instead of one above and one below.

going up: 0
going down: 0
2022-03-07T14:33:38.701Z
going up: 1
going down: 1
2022-03-07T14:33:39.213Z
going up: 2
going down: 2
2022-03-07T14:33:39.726Z
3
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This might help:

What if we started with this version instead?

function counter(value, limit) {
    if (value === limit) {
        console.log(value);
    } else {
        console.log('going up:', value);
        console .log ('*** Do some more stuff ***');
        console.log('going down:', value);
    }
}
counter(0, 3);

Then we would get this output:

going up: 0
*** Do some more stuff ***
going down: 0

Now let's replace that do-more-stuff with the result of calling counter (value + 1, limit), which is counter (1, 3), whose result would be:

going up: 1
*** Do some more stuff ***
going down: 1

Substituting that in, we get:

going up: 0
going up: 1
*** Do some more stuff ***
going down: 1
going down: 0

doing another level, we would call counter (2, 3) to get

going up: 2
*** Do some more stuff ***
going down: 2

and substituting that in to the above, we get

going up: 0
going up: 1
going up: 2
*** Do some more stuff ***
going down: 2
going down: 1
going down: 0

But now we call counter (3, 3), and the result is that we just log the value:

3

Substituting that in, we get

going up: 0
going up: 1
going up: 2
3
going down: 2
going down: 1
going down: 0

Of course at runtime there are no such actual substitutions. But we can think of the recursive call as something that gets stuck between "going up" and "going down", and any output from it will be placed between those two.

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!