Trampoline Pattern in Javascript

Saravanan M
3 min readJul 14, 2024

Recursion is a subject very close to my heart, and my affection for it led me to write two dedicated blogs on the subject( Think Recursively #1, #2 — yeah, shameless promotion)

As a functional programming developer, I prefer the elegance and clarity that recursion offers over traditional for loops, which are anyway off the table for me.

Photo by Nick Fewings on Unsplash

Recursion lets you ‘eat an elephant🐘 one bite at a time.’ by breaking down complex problems into smaller, manageable subproblems, you gradually solve the entire problem. However, despite its conceptual elegance, recursion can be inefficient in terms of both performance and memory usage, as evident in algorithms like those on competitive coding, where a bottom-up approach often outperforms top-down recursion

While we can’t do much about the performance aspect of recursion, we can address the memory issue to some extent in certain cases. Specifically, when the recursive call can be made tail recursive.

What is Tail Recursion?

Tail recursion is when the recursive call is the last statement executed by the function. Essentially, nothing is left to execute after the recursive call.

Consider this example:

function fibo(x) {
if (x < 2) return x;
return x + fibo(x - 1);
}

--

--

Saravanan M

Writes about Functional Programming, Web Development...