You already know that it is possible for a function to call another function, and that leads to an interesting question: is it possible for a function to call itself?
The answer is yes, and this method is called recursion. It might sound strange to make a function call itself, but not only it is allowed, this technique can be very useful sometimes.
The most classic example to demonstrate recursion would be the way how exponentiations are calculated.
Two ways to calculate exponentiation
First, let's think about how you would do it with loops. This example calculates a^b
:
1function power(a, b) {
2 let result = 1;
3
4 if (b === 0) {
5 return 1;
6 } else {
7 for (let i = 0; i < b; i++) {
8 result *= a;
9 }
10 return result;
11 }
12}
13
14console.log(power(5, 0));
15console.log(power(5, 1));
16console.log(power(5, 2));
17console.log(power(5, 3));
11
25
325
4125
The power()
function first tests if b
equals 0 since it is a special case. Any number raised to 0 equals 1. If b
is not 0, the function will use a loop to evaluate the exponentiation.
Alternatively, you can go with a recursive solution, which is much more elegant.
1function power(base, exponent) {
2 if (exponent == 0) {
3 return 1;
4 } else {
5 return base * power(base, exponent - 1);
6 }
7}