Recursion in JavaScript

Jas Spencer
2 min readApr 9, 2021

Getting asked what recursive functions are when you have no idea can be a bit terrifying.

To put it plain and simple: Recursion is a function that calls itself until a condition is met. Each language has its own syntax for setting it up, but in this post I’ll be using JavaScript as an example and from there it can be easily translated into the language of your choice.

Because reading a basic definition and seeing recursion work are two different things. I’m going to provide a simple example of recursion with the most common example of how to use it if you search the web: a factorial.

A factorial of a number or integer is the product of said integer and all integers below it. For example the factorial value of 5 is 120, or 5x4x3x2x1. Factorials are noted as n! in the case of our example 5! If you can pseudo code in your head really quickly you might be able to see how recursion can work as we’ll need to keep using multiplication until we have covered all the integers between 5, or n to use in a general setting, to 1.

Writing a recursive function is going to look similar to a loop but with a few differences. In writing a loop, the end value, or ending condition, is written at the end of all the logic. In recursion, it’s written at the beginning and is know as the base case.

function findFactorial(n) {
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
}

The base case is that opening if statement, the condition that the function has to meet in order to end, n must equal 0.

If it doesn’t, the function will be called again but will now call it with the value of n minus 1. The function will continue to call itself until the base case is met.

Walking through the steps:

We set an initial value of n, like 5.

As 5 is not equal to 0, we get the value of 5 times the new value of n, which is 4.

As 4 is still not equal to 0… this is where the recursion comes in.

The function calls itself until we meet the base case, by the time that happens, we’ll get 120, or 5x4x3x2x1.

Recursive functions sound daunting when first introduced, but there are so many more resources out there to improve learning. They may be a bit advanced but knowing how and when to use them might just save you in that next coding interview!

--

--

Jas Spencer

Software Engineer in NYC with expertise in Ruby on Rails, JavaScript, and React