Help understanding code

can anyone explain how this code works and comes with 8?


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

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

It’s recursive.
power(2,3) = 2 * power(2, 2)
However, power(2, 2) = 2 * power(2, 1)
power(2, 1) = 2 * power(2, 0)
And, power(2, 0) = 1.

So, power(2, 1) = 2 * 1,
power(2, 2) = 2 * 2 * 1,
And power(2,3) = 2 * 2 * 2 * 1 = 8

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums