What Is Tail Recursion In JavaScript?

Anisimov Kirill
2 min readApr 3, 2020

--

In this article, I want to speak about basic functional programming conception — Tail Recursion (Trail-end Recursion) and consider some ideas about the possible future of this feature.

To start let’s write a truly simple recursive factorial function. For example, this function could be this:

const factorial = (n) => {
if(n === 0){
return 1;
}
return n * factorial(n - 1);
}

Or that:

const factorial = (n, acc = 1) => {
if(n === 0){
return acc;
}
return factorial(n - 1, n * acc);
}

What’s the difference?

The first solution is typical, however, the second is tail-recursive.

The recursive solutions mentioned above look really pretty and easy for reading, but these approaches have some performance issues, as all recursive solutions require more memory than iterative ones. Besides the second approach could be sometimes optimized (depending on the language).

Many programming languages, especially functional ones (such as Haskell, List, Elixir, and Scala) have a conception called “Tail Call Optimization”. This optimization allows executing the recursive function with better performance. After Tail Call Optimization the function would have the same performance that has the iterative implementation. Sounds great, isn’t it? What’s about JavaScript? Does JavaScript optimize these functions?

Yes and no, it depends on an engine that your browser uses. For example, at present only WebKit engine (Safari browser) supports Tail Call Optimization. V8 (Google and all Chromium browsers) is currently developing it. Yes, that sounds not so great already… I think every developer should write a code that could be properly used even in the future.

--

--