Recursion

A function that calls itself is called recursive. You can make a function to call itself, as long as it takes care not to overflow the stack.

Recursion allows some functions to be written in a different style.

Below is an alternative implementation of power.

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

console.log(power(2, 3));
//!8```

Instead of inelegant(looping) implementation, the function calls itself multiple times with different arguments to achieve the repeated multiplication.

Note
This implementation is about 10 times slower than the looping version. The dilemma of speed versus elegance is an interesting one and the programmer must decide on an appropriate implementation.

Another example, in the code below, we create a countDownFrom function, which then calls itself via the function name countDownFrom. This creates a loop that counts down from 5 to 0.

snippet
```var countDownFrom = function countDownFrom(num) {
console.log(num);
num--; // change the parameter value
if (num & lt; 0) {
return false;
} // if num < 0 return function with no recursion
// could have also done arguments.callee(num) if it was an anonymous function
countDownFrom(num);
};

countDownFrom(5); // kick off the function, which logs separately 5,4,3,2,1,0```

In the earlier power function example, the inelegant (looping) version is still simple and we don't need to make with the recursive version. But recursion is not always just a less-efficient alternative to looping. Some problems are much easier to solve with recursion than with loops.

Related Tutorial
Follow Us
Contents