In simplest terms, recursion is repeating an object over a series of iterations. A real world example commonly used to describe this would be a room of mirrors. Something in front of one mirror will repeat in other mirrors facing it until it reaches a mirror where the reflection is not capable of replicating. Now lets get to some code!
Recursion In Code
In terms of coding, recursion is done by creating a function that calls itself in a repetitive pattern until a stopping condition is met. For those with some coding experience, this should sound very similar to an iteration by looping(for, while, do…while). Despite similar results and approaches, there are striking differences.
- Recursion: declarative repetition, function calling subset of a parameter, requires some degree of known, can be slower, use more memory(i.e. stack space), typically simpler to write
- Iteration(looping): imperative repetition, loop based
In contrasting between iteration and recursion there are some noticeable disadvantages that recursion has. Honestly, they are enough to start raising questions about whether its the right option. Of course this is only looking at programming languages where iteration through looping is possible.
The reason recursion would be used despite its striking downfalls includes varying aspects of simplicity and understanding. Instead of continuing to go over these aspects, lets just get to coding already!
Factorial
function factorial(n) {
if(n == 0) {
return 1
} else {
return n * factorial(n - 1);
}
}
The code above shows an anonymous function factorial that shows the core of what recursion is. You start out with a base case, i.e. if(n == 0), and then the recursive case that calls factorial inside itself while passing a subset of the parameter n, i.e. n – 1.
That’s simple enough to get, so play with that function in your console on your favorite browser. In part two of this article series, we’ll be digging a little deeper.