Skip to content

Proper tail calls: in the spec, only in Safari (ES2015)

  • What ES2015 “proper tail calls” (PTC) guarantee, and the exact rules for tail position.
  • Why the feature is in the specification but works only in Safari.
  • Three portable ways to write deep recursion: a loop, a trampoline and an explicit stack.

TL;DR: ECMAScript 2015 requires that a function call in tail position in strict mode code reuse the caller’s stack frame, so tail-recursive code can run at any depth. In practice only JavaScriptCore (Safari, since Safari 10) implements it. V8 (Chrome, Edge, Node.js, Deno) and SpiderMonkey (Firefox) do not, and there is no plan to change that. Do not rely on tail calls in code that must run outside Safari. Write deep recursion as a loop, a trampoline or an explicit stack.

The spec makes this a guarantee, not an optional “tail call optimization” (TCO).

Every call pushes a frame onto a size-limited call stack, so recursion over deep data fails with RangeError: Maximum call stack size exceeded. In Scheme, a call that is a function’s last action replaces the current frame, so tail recursion runs in constant stack space. ES2015 adopted that rule. The sample counts the revisions in an OrdersPortal order’s history, a linked chain from newest to oldest, with plain and tail recursion.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). ES modules are strict mode code, so the tail call below qualifies under the spec. All outputs shown were produced with Node.js 22.23; Node.js 24.22 gives the same results.

// tc1.mjs - OrdersPortal: an order's revision history is a linked chain (newest -> oldest).
// Modules are strict mode code, so the tail call below qualifies for ES2015 proper tail calls.
function buildChain(length) {
let node = null;
for (let i = 1; i <= length; i++) node = { revision: i, previous: node };
return node;
}
// Not a tail call: the addition happens after the recursive call returns.
function countRevisions(node) {
if (node === null) return 0;
return 1 + countRevisions(node.previous);
}
// Tail call: the recursive call is the last thing the function does.
function countRevisionsTail(node, count = 0) {
if (node === null) return count;
return countRevisionsTail(node.previous, count + 1);
}
for (const length of [1_000, 100_000]) {
const chain = buildChain(length);
for (const fn of [countRevisions, countRevisionsTail]) {
try {
console.log(length, fn.name, fn(chain));
} catch (e) {
console.log(length, fn.name, `${e.name}: ${e.message}`);
}
}
}

Output in Node.js:

1000 countRevisions 1000
1000 countRevisionsTail 1000
100000 countRevisions RangeError: Maximum call stack size exceeded
100000 countRevisionsTail RangeError: Maximum call stack size exceeded

Per the specification, countRevisionsTail should succeed at any length, and in Safari it does. V8 keeps every frame, so it overflows like the plain version. The limit is not a fixed call count: in one Node.js 22 run, a function with no parameters recursed about 12,500 times, one with five parameters about 6,300.

The spec defines tail calls with two static rules, IsInTailPosition and HasCallInTailPosition, and one runtime step, PrepareForTailCall, which discards the current execution context before the call.

A call is in tail position only if all of these hold:

  • The code is strict mode code: a module, a class body, or a function or script with "use strict". Sloppy mode is excluded because the non-standard fn.caller and fn.arguments properties let code inspect the stack that tail calls would erase.
  • It is inside a function body, not at the top level of a script or module.
  • That function is not a generator, an async function, an async generator or an async arrow function.
  • The call’s result is returned directly, with nothing left to do afterward.
// Fragment: which calls are in tail position (inside a strict-mode function)
return f(x); // yes
return cond ? f(x) : g(x); // yes: both branches
return a && f(x); // yes: the right operand of &&, || and ??
const step = (n) => f(n - 1); // yes: an arrow's concise body
return f(x) + 1; // no: the addition runs after f returns
return await f(x); // no: async functions never make tail calls
const r = f(x); return r; // no: the call is not in a return expression
f(x); // no: the function still returns undefined afterward
try { return f(x); } catch {} // no: the catch handler must stay active
try { /* ... */ } finally { return f(x); } // yes: a call in finally can be
return new F(x); // no: `new` is never a tail call

Making a call in tail position is not enough for portable code, because the guarantee exists only where it is implemented.

V8 implemented PTC in 2016 behind a flag (--harmony-tailcalls) but never shipped it, and later removed the flag. In its April 2016 blog post the V8 team gave two reasons. First, the elimination is implicit: nothing marks a tail call, so a small edit such as return 1 + f() silently turns constant stack use into an overflow. Second, eliminated frames disappear from the debugger’s call stack and from error.stack, which can break telemetry that collects client-side errors.

To address them, the Syntactic Tail Calls proposal, co-championed by committee members from Mozilla and Microsoft, suggested an explicit opt-in, return continue f(x), that makes the intent visible. It was discussed at TC39 in March and May 2016 and never advanced. TC39 now lists it as inactive: “Abandoned: the proposal became inactive and is no longer being pursued.”

The result, more than a decade later, is a spec requirement that two of the three major browser engines do not meet.

Tail calls only help linear recursion. Recursion over a tree calls itself inside a loop, so it can never be a tail call. OrdersPortal counts the products in its category tree after a bad import nested it 50,000 levels deep; the fix is an explicit stack that holds pending work in a heap array instead of call frames.

// tc3.mjs - OrdersPortal: count products in a category tree that a bad import made 50,000 levels deep.
// Tree recursion is not a tail call (the loop continues after each child returns),
// so no engine can optimize it. An explicit stack moves the depth from the call stack to the heap.
function buildCategories(depth, productsPerLevel) {
const root = { name: 'root', products: productsPerLevel, children: [] };
let node = root;
for (let level = 1; level < depth; level++) {
const child = { name: `level-${level}`, products: productsPerLevel, children: [] };
node.children.push(child, { name: `leaf-${level}`, products: 1, children: [] });
node = child;
}
return root;
}
function countProductsRecursive(category) {
let total = category.products;
for (const child of category.children) total += countProductsRecursive(child);
return total;
}
function countProducts(root) {
let total = 0;
const stack = [root];
while (stack.length > 0) {
const category = stack.pop();
total += category.products;
for (const child of category.children) stack.push(child);
}
return total;
}
for (const depth of [100, 50_000]) {
const tree = buildCategories(depth, 3);
let recursive;
try {
recursive = countProductsRecursive(tree);
} catch (e) {
recursive = `${e.name}: ${e.message}`;
}
console.log(depth, '| recursive:', recursive, '| explicit stack:', countProducts(tree));
}

Output:

100 | recursive: 399 | explicit stack: 399
50000 | recursive: RangeError: Maximum call stack size exceeded | explicit stack: 199999

The explicit stack visits children in reverse order; push them in reverse if order matters. For linear recursion such as the revision chain, two simpler patterns work everywhere:

// tc2.mjs - two portable alternatives that work in every engine.
function buildChain(length) {
let node = null;
for (let i = 1; i <= length; i++) node = { revision: i, previous: node };
return node;
}
// 1. A loop: the tail-recursive function rewritten mechanically.
function countRevisionsLoop(node) {
let count = 0;
while (node !== null) {
count += 1;
node = node.previous;
}
return count;
}
// 2. A trampoline: the function returns a thunk instead of calling itself.
const trampoline = (fn) => (...args) => {
let result = fn(...args);
while (typeof result === 'function') result = result();
return result;
};
const countRevisionsTramp = trampoline(function step(node, count = 0) {
return node === null ? count : () => step(node.previous, count + 1);
});
const chain = buildChain(1_000_000);
console.log(countRevisionsLoop(chain)); // 1000000
console.log(countRevisionsTramp(chain)); // 1000000

Any tail-recursive function converts to a loop: parameters become variables and the tail call becomes reassignment. A trampoline keeps the recursive shape, which helps with mutual recursion, at the cost of one closure per step; it cannot return a function as its final value.

  • Testing in Safari only. Tail-recursive code that passes in Safari overflows in Chrome, Firefox and Node.js.
  • Assuming a transpiler adds PTC. Neither TypeScript nor Babel rewrites tail calls; they leave the behavior to the engine.
  • Thinking return await f() or return f() + 1 is a tail call. Neither is: async functions are excluded and the addition happens afterward.
  • Raising the stack size instead of fixing the algorithm. node --stack-size is a V8 option, not a supported Node.js setting. Set above what the operating system’s thread stack provides, it crashes the process instead of throwing RangeError: node --stack-size=200000 tc1.mjs ends with a segmentation fault on Linux with the default 8 MB stack.
  • Relying on the recursion limit as a number. It depends on the engine, frame size and platform. Design for unbounded input, or validate depth up front.
Technique Works in Stack use Best for
Plain recursion All engines Grows with depth Inputs with a known small depth (UI trees, ASTs of normal code)
Tail recursion relying on PTC Safari/JavaScriptCore only Constant there, grows elsewhere Safari-only code; avoid otherwise
Loop All engines Constant Linear recursion: lists, counters, accumulators
Trampoline All engines Constant Mutual recursion, interpreters, state machines
Explicit stack or queue All engines Constant (data on the heap) Trees and graphs of unknown depth

MDN’s compatibility data does not track proper tail calls. The kangax ECMAScript compatibility table, maintained by the community, reports:

  • Safari / JavaScriptCore: supported since Safari 10.
  • Chrome / V8, Node.js, Deno: not supported. Chrome 51 to 60 had it only behind flags; since Chrome 61 it is gone, and since Node.js 8.2.1 the --harmony-tailcalls flag no longer exists.
  • Firefox / SpiderMonkey: not supported.
  • Hermes (React Native): not supported.
  • Embedded engines: XS and Duktape 2.0 support it.

No polyfill is possible, since tail calls depend on how the engine manages the stack. TypeScript has no option for them.

1. Is return n * factorial(n - 1) a tail call? How do you make it one? No: the multiplication happens after the call returns. Add an accumulator: return factorial(n - 1, n * acc). That is a tail call, but outside Safari it still overflows, so in portable code write the accumulator version as a loop.

2. Why are tail calls restricted to strict mode, and why are async functions excluded? Sloppy mode’s non-standard fn.caller and fn.arguments expose the call stack, which tail calls would remove. An async function has to wrap its result in a promise and resume after await, so its frame always has work left after the call.

3. Senior scenario: a teammate submits a JSON schema validator that recurses through nested objects and says it is safe because “JavaScript has tail call optimization.” The validator runs in Node.js on user-supplied documents. What do you say? Node.js runs on V8, which has no tail calls, and tree recursion is not in tail position anyway. A deeply nested payload can throw RangeError and becomes a denial-of-service vector. Rewrite the traversal with an explicit stack, enforce a maximum depth as a deliberate policy, and add a test with a document nested beyond it.

  • ES2015 specifies proper tail calls for strict mode code, but only Safari’s JavaScriptCore ships them.
  • + 1 after the call, await, try blocks and sloppy mode all disqualify a call.
  • V8 declined because implicit tail calls are hard to spot and erase stack frames; the explicit syntax proposal was abandoned.
  • For portable code, use a loop or trampoline for linear recursion and an explicit stack for trees.