1

// Calculate a Number to a Specific Power
// create a function which takes a number and an exponent and
// recursively calls itself to calculate the product
// e.g.

let base = 2;
let exponent = 4;
let product = power(base, exponent)  // 2 to the 4th power

function power(base, exponent) {
  //base case
  if (exponent === 0) {
    return 1;
  }

  return base * power(base, exponent--);
}

console.log(product);  // 16
Álvaro González
  • 142,137
  • 41
  • 261
  • 360

3 Answers3

5

You need first to do decrement - --exponent. When you do exponent--, the value is passed into the function, then will decrement it's value. So you every time pass the same value to the function, after it decrement it, but this decrement is useless.

So your statement can be equal to something this

return base * power(base, exponent);
exponent = exponent - 1;

And because you return from that line, the else is useless. You can see that the same exponent is passed every time.

Check this code.

let base = 2;
let exponent = 4;
let product = power(base, exponent); 

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

  return base * power(base, --exponent);
}

console.log(product);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
5

In the case, where you never use the decremented variable again, I suggest to use simply a subtraction, wihthout decrement, because the assignment of the new value to the variable is an unnecessary operation.

return base * power(base, exponent - 1);

BTW, the decrement operator --

... decrements (subtracts one from) its operand and returns a value.

  • If used postfix (for example, x--), then it returns the value before decrementing.
  • If used prefix (for example, --x), then it returns the value after decrementing.
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This is what I read and could answer your question:exponent-- returns exponent then minus one to it, which in theory results in the creation of a temporary variable storing the value of exponent before the decrementing operation was applied".

So in your case when you call power(base, exponent--) with exponent=4 this is what actually goes power(base, 4) and after this exponent was decrease by 1 one become 1.

See below example. I am printing exponent value and every time it is 2.(as decrement occur after excution of that statement).

let base = 2;
let exponent = 2;
var count=0;
let product = power(base, exponent, count)  // 2 to the 4th power


function power(base, exponent, count) {
  //base case
  console.log(exponent);
  if (exponent === 0) {
    return 1;
  }
  if(count === 4)
  {
    count =0;
    return 1;
  }

  return base * power(base, exponent--,++count);
}

To correct your code just replace exponent-- with --exponent.

yajiv
  • 2,901
  • 2
  • 15
  • 25