Member-only story

Recursion and tail recursion with JavaScript

Kristijan
3 min readOct 22, 2020

--

Recursion is one of the topics that everyone covers, no matter which programming language you are learning. Probably in the first few classes of any beginner courses. Still, many people struggle with understanding it. This post covers what recursion is, what to watch for when writing a recursive function. Also, there is a section on a tail recursion, a bit more optimized version of recursion.

What is recursion?

A commonly used definition of recursion is that it is a self-invoking function. But what does that mean? Usually, you write the function, and then you call it. With recursion, inside of the body of the function, you also call it.

function recursiveFunction() {
// some code
recursiveFunction();
}

Looking at snippet about, you might think, this is an infinite loop. What about stack overflow? And you are right. When writing recursion, you need to pay special attention to the end case. But there is a bit more about that one bellow. First, answer to the other question you might ask.

Why and when would you use recursion?

There are different use cases, and everyone has their own opinion. I think they are great when you need to loop something, but you don’t know how many times. Long pull from the server, where you are fetching data as long…

--

--

No responses yet