Tail Call Optimization (TCO) in JavaScript
A stack frame-by-frame breakdown of how TCP improves your memory footprint
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")…