Power
Now a function with two arguments. Only one of them shrinks each call β that's the one driving you toward the base case.
Raising base to the exp power means multiplying base by itself exp
times. Recursively: base^exp = base Γ base^(exp-1), and base^0 = 1.
function power(base, exp) {
if (exp === 0) return 1; // base case: anything^0 is 1
return base * power(base, exp - 1); // base stays, exp shrinks
}
power(2, 5); // 32
Watch which argument changes: base is passed along unchanged, while exp
counts down to 0. That's deliberate β the shrinking argument is what reaches
the base case.
Your task
Write power(base, exp) that returns base raised to exp without using
** or Math.pow. Assume exp >= 0.
β‘ 45 XP
π§± Code blocks
Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.
solution.jsRuns in your browser
Loading editorβ¦
Tests5 to pass
power(2, 5) β 32
power(5, 0) β 1
power(3, 3) β 27
power(10, 1) β 10
power(7, 2) β 49
Run your code to check these.