Member-only story
Recursion vs. Loops in JavaScript
Recursion doesn’t have to be scary
Recursion is the nemesis of every developer, only matched in power by its friend, regular expressions.
Recursion can be hard to wrap your head around for a couple of reasons. First, you have to grasp the concept of a function calling itself. Second, you have to understand the difference between the base case and the recursive case, or else you may find yourself stuck in an infinite loop until you cause a stack overflow.
If you can master those two concepts, recursion isn’t as scary or complex as you think. Recursive code is often shorter to write and (in some cases) easier to read.
Let’s walk through five code examples together. We’ll solve each problem first by using a loop, then we’ll solve it using recursion. Which approach is better? That’s for you to decide.
Example #1: Factorial
Let’s write a function that allows us to calculate the factorial for positive integers. Factorials are written like this: 5!
. And the formula for a factorial looks like this:
n! = n * (n - 1) * (n - 2) * ... * 1
So 5!
would be:
5! = 5 * 4 * 3 * 2 * 1 = 120