1

I'm trying to learn recursion in Javascript and wrote this to trace a simple recursive function.

function count(num){

console.log(num + " top");
if (num===5)
return console.log("It has ended.");
count(num+1);
console.log(num + " bottom");
}

count(1);

Here's the output:

1 top
2 top
3 top
4 top
5 top
It has ended.
4 bottom
3 bottom
2 bottom
1 bottom

So what's happening here? Is there something wrong with my base condition? Is the log showing what's put on and taken off the stack? I would have expected the function to stop at "It has ended" and I'm not sure why it doesn't.

Thanks.

rswerve
  • 169
  • 1
  • 3
  • 7
  • The function is called multiple times… It only stops once at "It has ended", but four times it does not. – Bergi Sep 18 '15 at 15:27
  • 1
    Maybe this will help: [Understanding how recursive functions work](http://stackoverflow.com/q/25676961/1492578) – John Bupit Sep 18 '15 at 15:33
  • I think I may need to read that. Recursion makes my head hurt and I basically think it's magic. – Andy Sep 18 '15 at 15:38

2 Answers2

2

When you get to 5, the return statement fires. That means that the 5th time count is called it won't call count again and then it won't call console.log again.

When it returns from the 5th call, it resumes the 4th call.

In the 4th call, count is 4 (count is a local variable and you have a different one for each call to count) so it runs the final console.log statement in the function, reaches the end of the function and returns undefined. The third call then resumes, and so on.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. I'm almost there. When `count(num+1)` is called, the entire function repeats, and that's why we see the ascending count in the log. Then the condition is met and "It has ended" gets logged. But what is going on when the descending count is logged *after* the condition is met? Which is to say, I guess I don't yet understand your final two paragraphs. – rswerve Sep 18 '15 at 22:12
  • @rswerve — It returns from the function it called and resumes running the previous function (which is the same function, just with different arguments). – Quentin Sep 19 '15 at 07:33
0

The point is, your funcion prints top and bottom, if not terminated before. the call is made inbetween of top and bottom as well as the return.

first   second  third   4th     5h call of function
1 top
        2 top
                3 top
                        4 top
                                5 top
                                It has ended.
                        4 bottom
                3 bottom
        2 bottom
1 bottom 
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392