function func(n) {
if(n > 0) func(n-1)
console.log(n)
}
func(10)
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.
function func(n) {
console.log(n)
if(n > 0)
func(n-1)
console.log(n)
}
func(3)
No comments:
Post a Comment
comment here