Tail call optimization (TCO) in Node v6

Daishi Kato
Dec 8, 2016 · 2 min read

Node v6 supports proper tail calls also known as tail call optimization, according to node.green.

What is a tail call?

It’s a function call that is done at the end of a function. Usually, when a function is called, it returns, so the calling function has to be memorized. However, if it’s a tail call, the function doesn’t have to return, or return to the original call in the call chain. Technically, it doesn’t consume stack for tail calls, so there’s no stack overflow.

Example in Node v6

You need to add flags, but this is how it works:

$ node --harmony --use_strict
> function f() { return f(); }
> f()

It runs forever, just like an infinite loop.

Let’s disable TCO by removing the flags, and see how it goes:

$ node
> function f() { return f(); }
> f()
RangeError: Maximum call stack size exceeded
at f (repl:1:19)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)
at f (repl:1:31)

You can add console.log to see more convincingly.

node --harmony --use_strict 
> function f(x) { console.log(x); return f(x + 1); }
> f(0)

And, it continues forever, maybe.

A note

One thing I found, which is the reason of this post, is the following.

function f(x) { console.log(x); f(x + 1); }

This code looks like a proper tail call, but it doesn’t work with Node v6. You need to explicitly add “return” to enable TCO.


Is this expected in the spec?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store