How TCO works

Let's compare two stack frames, one without TCO and the other with TCO. Let's have a look at the following code first:

function a(x){    y = x + 2;    return b(y);}function b(y){    z = y + 3;    return z;}console.log(a(1)); // 6

Once allocated to memory, without using TCO, the three stack frames from of the previous code would look like the following diagram:

A typical last-in, first-out (LIFO) call stack

Once value 6 is assigned to variable z, the stack frame is ready to be popped. In this case, stack frame 2 is kept entirely in memory only to keep the address of console.log(). This is where TCO can make a difference. If, before calling ...

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.