'Exponent code, i don't understad code behaviour

This is the code for exponent compute:

var exponent = function(a, n){
  if(n === 0) {
    return 1;
  }
  else {
    return a * exponent(a, n-1)
  }
};

console.log(exponent(5,3));

I don't understand this line:

return a * exponent(a, n-1)

What does exponent(a, n-1) mean? Especially n-1?



Solution 1:[1]

In your example

exponent(5, 3)

On that line, it equal to

5 * exponent(5, 2) // 2 = 3 - 1

then, it equal to

5 * (5 * exponent(5, 1)) // 1 = 2 - 1

= 5 * (5 * (5 * exponent(5, 0))) // 0 = 1 - 1

= 5 * (5 * (5 * 1)) // exponent(5, 0) = 1 because n === 0

...

Solution 2:[2]

This is a recursive function. The recursive call counts down from n to 1 by calling itself with n-1 as argument. So you get this:

exponent(5, 0) == 1
exponent(5, 1) == 5 * exponent(5, 1 - 1) == 5 * exponent(5, 0) == 5 * 1 == 5
exponent(5, 2) == 5 * exponent(5, 2 - 1) == 5 * exponent(5, 1) == 5 * 5 * exponent(5, 1 - 1) == 5 * 5 * exponent(5, 0) == 5 * 5 * 1 == 25
// ... and so on

So n - 1 is essentially a counter, counting down the number of times the function still has to repeat itself.

Solution 3:[3]

This is a recursive function for calculating a raised to a power n. If the exponent is 0, you're done and 1 is returned. Otherwise a times the result of a raised to the power n-1 is returned - which is recursive...

Solution 4:[4]

Your function is a recursive function, lets say a = 2 and n = 3, on your first iteration, n = 3 - 1 = 2and a = 2 * 2 = 4 since n = 2 != 0, your function iterates again, second iteration, n = 2 - 1 = 1 and a = 4 * 2 = 8 third iteration, n = 1 - 1 = 0 since n = 0 then it stops.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nguyen Phong Thien
Solution 2 jvdmr
Solution 3 Jay Buckman
Solution 4 Thapelo Masethe