Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why recursion occurs in reverse

The question is, does the function pause at the line where the function is called again or does it executes fully and then come back to that line (where the same function is called).

I also have this example which shows that recursion occurs in reverse (I guess each inner function keep reference to its outer function and execution occurs in reverse to normal order).

Please go in much details as possible.

function func(n) {
  if(n > 0) func(n-1) 
  console.log(n)
}

func(10) // 1,2,3,4,5,6,7,8,9,10

// while I was expecting 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
like image 336
Ninja47 Avatar asked May 31 '26 03:05

Ninja47


1 Answers

I would suggest to use debugger tools in chrome to trace the codes execution. Recursion does happen backwards because it has to meet your base case in order to exit. Every time it does not meet your base case the current running function is put in call stack (in JS). In you case func(n-1 gets called and previous func is put in call stack. Once your base case is met, your funcs that are in call stack start to continue running (from leftover line -> console.log). Since the nature of stacks is Last In First Out (LIFO), you functions run in reverse.

like image 177
Ziyo Avatar answered Jun 01 '26 16:06

Ziyo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!