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
(Note to self: embed the video using Lite YouTube Embed.)
- 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.
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