What is tail-call optimization (TCO)?

suggest change

A call is in tail position when its result is returned directly, with no additional work required by the caller:

"use strict";

function a() {
  return b(); // Tail call: a() returns exactly what b() returns.
}

function b() {
  return 1;
}

a();

An implementation that performs proper tail calls can reuse the current call frame instead of adding another frame to the stack. This allows some tail-recursive algorithms to run without the stack growing for every recursive call.

ECMAScript specifies proper tail calls only for calls in tail position in strict-mode code. Runtime support is not universal, however, so application code should not assume that tail recursion can continue indefinitely. Use an iterative algorithm when stack depth must be predictable.

Tail-call optimization does not apply merely because one function calls another. For example, return 1 + b() is not a tail call because the caller must still add 1 after b() returns. A transpiler also cannot generally provide native stack-frame reuse without changing the program into a different control-flow representation, such as a loop or trampoline.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents