liveBook · Manning

Trampolining

As explained in Functional Programming in JavaScript

A technique for simulating tail recursion by repeatedly invoking thunks or continuations in an iterative loop.

Trampolining simulates tail recursion with an iterative loop, helping control function stack growth when JavaScript lacks native tail-call optimization. A trampoline repeatedly invokes a function until a stopping condition occurs. section 7.4

Each repeated step can be wrapped in a thunk: a parameterless function that delays evaluating an argument expression until another function invokes it. The technique is introduced as a workaround rather than developed in detail. section 7.4

const factorial = (n, current = 1) => 
   (n === 1) ? current 
    : factorial(n - 1, n * current);      

Use the tail-recursive factorial example to see the recursive form that trampolining is intended to support when tail-call optimization is unavailable. section 7.4

How Functional Programming in JavaScript covers it

How deep it goes
Defines trampolines and thunks, but stops short of implementation details and recommends further research.
Examples
Uses tail-recursive factorial examples to motivate the need for trampolining.
What it assumes
Assumes familiarity with recursion and tail-recursive calls while defining thunks in plain language.
What you can do after
Evaluate when trampolining can work around missing native tail-call optimization in JavaScript.
How it connects
Connects trampolining with recursion, tail-call optimization, thunks, iterative loops, and Babel transpilation.

Also explained in

Compare how 2 books explain trampolining →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.