+ 7
How does this Recursive function work
function power(base,exponent){ if(exponent==0){ return 1; }else{ return base* power(base,exponent-1); } } console.log(power(2,3)); // 8 How did JavaScript did the calculation that provided 8 please explain in detail to me
3 Réponses
+ 3
JavaScript done this like: -
1. power(2, 3) , where values 2 and 3 is passed to the function named power.
2. It checks whether exponent is equal to 0 or not. In this case it is equal to 3 and hence the condition becomes false and code in the else block will run.
3. In the else block it returns the expression as base * power(base, exponent-1).
4. In the example above, it can be demonstrated as 2*power(2, 3-1)
5. In the step above, an recursion occurs and power function calls itself.
6.Now in the power function, the values 2 and 2 is passed just as it was passed above. Ex: power(2, 2)
7. Now it again checks the condition that whether the exponent which is 2 in this case is equal to 0 or not and again it evaluates to false and the code in the else block is run.
8. It repeatedly executes just like in a loop and can be demonstrated as power(2,3) = 2 * power(2,2) = 2 * 2 * power(2,1) = 2 * 2 * 2 * power(2,0) = 2 * 2 * 2 * 1.
+ 7
Base=2
Exponent =3
1st time
(2,3)
Returns (2 * return of (2,3-1))
2nd time
(2,2)
Returns (2* return of (2,2-1))
3rd time
(2,1)
Returns (2*return of (2,1-1))
4th time
(2,0)
Returns 1 as if condition satisfied
Finally
4th return 1
3rd return 2*1
2nd return 2*2
1st return 2*4
We get answer 8
As this time function call 4 times if you cange the number follow the pattern only number of times function call change.
+ 6
power(2,3) = 2 * power(2,2) = 2 * 2 * power(2,1) = 2 * 2 * 2 * power(2,0) = 2 * 2 * 2 * 1