Home > Software engineering >  unable to understand recursive pattern and its function call
unable to understand recursive pattern and its function call

Time:04-05

Recently i started to learn recursion in JavaScript.

i never called defined function in its own function. what is this called?

i'm unable to understand how this recur(n - 1) working.

i tried to check how it working in chrome debugger, but there is no output too.

How here recur(n - 1) working?

function recur(n) {
 if(n === 1) return 1

 return n * recur(n - 1);
 // How here recur(n - 1) working?
 // 5 * 5 - 1 = 24
 // 4 * 4 - 1 = 15

}

recur(5);

CodePudding user response:

So when you do return n * recur(n - 1), the first thing that is calculated is recur(n - 1). What happens is the following

recur(5) = 5 * recur(5 - 1)
recur(4) = 4 * recur(4 - 1)
recur(3) = 3 * recur(3 - 1)
recur(2) = 2 * recur(2 - 1)
recur(1) = 1 => the bottom of the recursion. Now it starts to go back:
recur(2) = 2 * recur(1) = 2
recur(3) = 3 * recur(2) = 3 * 2 = 6
recur(4) = 4 * recur(3) = 4 * 6 = 24
recur(5) = 5 * recur(4) = 5 * 24 = 120

Basically, until a function of recur(n - 1) returns something concrete, like the bottom of the recursion in your case 1, the method calls recur once again, and again and so on. After you go to the bottom, then the functions start to resolve in the reverse order.

CodePudding user response:

The recursive function is calculating the factorial of n.
The function will call itself until it reaches a base case.
You have one base case: when n is 1 then return 1.

If you call it with say 5 then it works as follows:

recur(5) =>  
5 * recur(4) =>  
5 * 4 * recur(3) =>  
5 * 4 * 3 * recur(2) =>  
5 * 4 * 3 * 2 * recur(1) =>  
5 * 4 * 3 * 2 * 1 =>  
120

So the result will be 120 for n=5.

  • Related