Recursion: Compute the exponent of a number

Hello Everyone.

I was doing this exercise, which is to find the exponent of a number using recursion. I actually don’t have problem in understanding the code. But I have a simple question. There are two solutions, which I believe they’re right as they’re producing the right answer for this exercise. I would like to know if solution 1 is better than solution 2 or vice versa? and why? Or are they both correct?

(NOTE: The difference between both of the solutions is just the base case of the recursion.)

Solution 1.

``````function power(base, exponent) {
if (exponent === 1) {
return base;
} else {
return base * power(base ,exponent-1);
}
}

console.log(power(8,2)); //64

``````

Solution 2.

``````function power(base, exponent) {
if (exponent === 0) {
return 1;
} else {
return base * power(base ,exponent-1);
}
}

console.log(power(8,2)); //64

``````

The first one gets called one fewer time, so it’s that tiny bit more efficient. Unless you need to handle the case where the original exponent passed in is 0.

1 Like

I got it!! Thanks!!