My notes on "Tail Call Optimization: The Musical!"

Published on in JavaScript

Last updated on

My quick notes on a funny but informative video (11:27) that explains how tail call optimization (TCO) works. Bonus: does JS support TCO? Spoiler: yes but no.

Table of contents

The video

Watch the video on YouTube

(Note to self: embed the video using Lite YouTube Embed.)

My notes

  • Tail call = a function call at the very end of a function, i.e. the function call has to be the very last thing that the function does.
  • Tail call optimization (TCO) = if the language (and engine) supports TCO, tail calls are removed from the call stack because they are kind of unnecessarily there (because of the tail position).
    • Pro: You don't get errors saying "Maximum call stack size exceeded" (Chrome) or "Too much recursion" (Firefox) or "Stack overflow" (some other contexts).
    • Con: Stack traces have less information (because tail calls have been removed from the call stack), making debugging errors potentially more difficult.

Bonus: Does JavaScript support TCO?

Not in the video but relevant: ECMAScript 6 offers TCO, but TCO "isn't supported by many [JavaScript] engines and that may never change." Source: Tail call optimization in ECMAScript 6 by Dr. Axel Rauschmayer.

The ECMAScript 6 compatibility table shows that there indeed are not many browsers/engines that support TCO – only these (as of Aug 26, 2021):

  • Safari 14+
  • iOS Safari 12+
  • WebKit, the browser engine used by Safari and iOS Safari
  • Kinoma XS6, "a JavaScript runtime optimized for the applications that power IoT devices"