Tail Call Optimization (TCO) in JavaScript

A stack frame-by-frame breakdown of how TCP improves your memory footprint

Jim Rottinger
HackerNoon.com
Published in
8 min readMar 6, 2016

--

Every time we call a function, we stack another rock on top. This obviously does not scale.

One of the behind-the-scenes changes that is coming with ES6 is support for tail call optimization (TCO). Tail call optimization means that, if the last expression in a function is a call to another function, then the engine will optimize so that the call stack does not grow. Let’s take a look.

What is Tail Call Optimization?

Tail call optimization means that it is possible to call a function from another function without growing the call stack. In order to understand the importance of that statement, we have to talk about how the stack works.

You might be familiar with the word stack considering it is one of the most commonly seen data structures. It is a LIFO (last-in first-out) queue with two primary operators — push and pop. The “call stack” is an implementation of the stack data structure used to navigate a program through function calls and store variables local to those functions. Consider the following code block:

(function wrapperFunction(){
console.log("Executing in the Wrapper Function");
function functionA(a,b,c) {
console.log("Executing in Function A")

--

--

Jim Rottinger
HackerNoon.com

8+ years working with startups 💡. Currently working at Square — formerly at Google, Looker, Weebly. Writing about JavaScript | Web Development | Programming