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
How could we write a function for this? One approach would be to use a while loop
. We can create a variable for our result
and then multiply it with x
in a loop, decrementing x
by 1 each time. The code looks like this:
Note that we’ve also handled bad inputs less than 0, and we’ve simplified the cases of 0 and 1 since 0!
and 1!
both equal 1.
So that’s a solution that utilizes a loop. What if we wanted to write this function recursively? A recursive solution could look like this: