Glendon Philipp Baculio - 4 months ago 9

Javascript Question

I am having a hard time understanding recursion on eloquent javascript, It easy to know what is happening but I cannot understand why..

`function power(base, exponent) {`

if (exponent == 0)

return 1;

else

return base * power(base, exponent - 1); /* 2*2*2, this returns only base?

i thought at first it was, 2*(2,3-1) so it would return 2*(2,2)?

calling itself until reach 0, so why exponent is out?*/

}

console.log(power(2, 3));

// → 8

Answer

Recursive functions can often be expressed as a loop. See this adaptation:

```
function power(base, exponent) {
var result = 1;
for (var i = 0; i < exponent; i++)
result *= base;
return result;
}
```

As you can see, the exponent doesn't play a role at all in what is output, it just represents the number of loops to make.

In the world of recursion, the exponent represents the number of times the function has yet to call itself before it can return.

This YouTube video visualizes recursion nicely: Computerphile

Source (Stackoverflow)

Comments