I’ll walk you through two popular JS recursion examples in 10 minutes so you can finally understand how recursion works in JavaScript.
Recursion is simply when a function calls itself.
Lets jump right in and take a look at probably the most famous recursion example. This example returns the factorial of a supplied integer:
function factorial(x) {
if (x < 0) return;
if (x === 0) return 1;
return x * factorial(x - 1);
}factorial(3);
// 6
Woah. It’s Okay if that makes no sense to you. The important part is happening on line 4: return x * factorial(x — 1);
. As you can see, the function is actually calling itself again ( factorial(x-1)
), but with a parameter that is one less than when it was called the first time. This makes it a recursive function.
Before I break down that code example any further, it’s important you understand what factorials are.
To get the factorial of a number you multiply that number by itself minus one until you reach the number one.
Example 1: The factorial of 4 is 4 * 3 * 2 * 1, or 24.
Example 2: The factorial of 2 is just 2 * 1, or 2.
Awesome, now that our High School Math lesson is over, we can return to the good stuff!
#javascript #web-development #developer