0

function pow(x, n) { if (n == 1) { return x; } else { return x * pow(x, n - 1); } } alert( pow(2, 3) );

How to work this function

12th May 2021, 3:35 AM
Animesh Mahato
2 Réponses
+ 2
pow(2,3) 2*pow(2,2) 2*2*pow(2,1) 2*2*2 8
12th May 2021, 3:44 AM
TOLUENE
TOLUENE - avatar
+ 1
This is called Recursion means function calling function itself until the condition is not satisfying. So here pow(x, n) = pow(2, 3) n = 3, x = 2 for n = 3, n == 1 //false so else will execute = x * pow(x, n - 1) = 2 * pow(2, 2) //now here n = 2 so for n = 2, n == 1 is false so else will execute = 2 * (2 * pow(2, 1)) now here n = 1, so n == 1 will be true and method will return x means 2 so finally = 2 * 2 * 2 = 8
12th May 2021, 4:28 AM
A͢J
A͢J - avatar