Adsense

why recursion occurs in reverse?

 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
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) //output 3 2 1

   if(n > 0)

      func(n-1) 

   console.log(n) //output 1 2 3

}

func(3) //Taking small digit for quick explanation

recursion



No comments:

Post a Comment

comment here

newest questions on wordpress