Recursion

Peter Kim
Peter Kim
Aug 27, 2017 · 2 min read

Let’s talk about recursion! What is a recursive function?

Recursion is when you use something over and over again until there is a stop. A recursive function will repeatedly call itself until the base case is hit.

When you first start trying to implement recursion, it is hard to know where to even start. There’s a difference between calling a function multiple times and calling a function that calls itself. Take a look at the following below:

let factorial = (number) => {
if (number === 1){
return number
} else {
return number * factorial(number - 1)
}
}
factorial(3) => 6
factorial(4) => 24

Here is a basic recursive function that gets the factorial of the number being passed in. Let’s take a look at what’s going on.

When a number is passed in, the function checks the number. Since we’re checking for factorials, we can assume number 1 will be the lowest number. This means that we can return 1 for the base case. A base case is pretty much how the recursive function would stop. If we passed in number 2, since it is not satisfied in the first condition ( number is not 1), it will return the number (2) and multiply it by the return value of the factorial of 1, which would return 1. 1 x 2 = 2 ? Yup. That seems right.

If we passed in 3 as the argument, the first run through would return 3 and multiply it by factorial(2), which would return 2 and multiply it by factorial(1), which returns 1. 3 x 2 x 1 = 6 ? Yup!

I know this is much easier to read than it is to implement but the more you implement, the more you get used to setting it up.

Some things to look out for:
- If you use recursion, make sure to avoid an infinite call stack by changing the input into the recursive function. If in the example above, I decided to return the number and multiply it by factorial(number), it would constantly call itself with no change and thus make you stuck in an infinite loop. See it?
- Although recursive functions are cool, sometimes a simple for loop may be just as efficient.

)

Peter Kim

Peter Kim

Full Stack Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade