Let's get recursive
A superficial examination of recursion in JavaScript
May 8, 2015
Recursion happens when a function calls itself.
Let's start with a simple example, where the function countDown will log the first argument to the console and then calls itself, but this time with the argument - 1.
Take note that countDown also breaks out of the loop once the argument hits 0.
We can see how this example is really similar to a loop.
According to my various readings on recursion, loops will usually get the job done just fine. They cost less memory as well. But sometimes recursion looks better and is more logical to the human programmer.
One classic example of recursion is calculating a factorial. This is thoroughly worked through in the JavaScript Recursion course on Codecademy.
The factorial of a number is calculated by multiplying the number times the number minus 1, times the number minus 2, and all the way down until you hit 1.
So, if you wanted the factorial of 5, you multiply 5 * 4 * 3 * 2 * 1. Let's look at this in JavaScript.
This is just a very first toe-dipping into recursion, but if you can grasp these simple concepts you'll be on your way to understanding the real stuff.