Tail call optimization (TCO) in Node v6

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(); }
undefined
> f()
$ node
> function f() { return f(); }
undefined
> 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)
node --harmony --use_strict 
> function f(x) { console.log(x); return f(x + 1); }
undefined
> f(0)
1
2
3
4
5
6
7
8
9
10
11

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); }

Question

Is this expected in the spec?

A freelance programmer. I’m interested in working remotely with people abroad: https://contact.axlight.com https://blog.axlight.com

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