I’m having a hard time understanding the else block. I know it’s supposed to raise the base parameter to the exponent parameter. But how does it work?
var power = function(base, exponent){
if (exponent === 0){
return 1;
}
else{
return base * power(base, exponent - 1);
}
};
power(2, 2);
is really just
base * power(base, exponent - 1). But if we keep thinking about what is happening in those function calls, we see this:Let’s try
power(2, 4):power(2, 4 - 1)simplifies towhich simplifies to
which simplifies to
and that simplifies to
1sinceexponentwill be0. When we put it all together this is what we get: