Recursion Dolls — Algorithms

Open matryoshka dolls one by one down to the base case, then guess the result: 14 levels of recursion, the call stack and return values.

What you learn in this game

A recursive function calls itself with a smaller problem. Each call waits on the call stack until the call below it comes back: on Bu Warti's rack, every call is one carrier on one step. The base case is a problem small enough to answer at once, without calling again. There the stack stops growing, and values start climbing back up from carrier to carrier. Without a base case, the calls never run out. JavaScript does not spin forever: after a few thousand calls its stack is full and it throws RangeError: Maximum call stack size exceeded.

A function may call itself more than once. Each call becomes a branch, so the carriers are no longer one straight line but a tree. JavaScript still works through them one at a time: the left branch is opened all the way and comes back before the right branch opens. The same problem can be opened several times on different branches.

When the recursive line is only return f(...), with nothing waiting for its result, the value from the base case climbs unchanged to the top carrier. A call like this is a tail call. The JavaScript standard since ES2015 lets an engine drop the caller's frame on a tail call, but only Safari does, and only in strict mode. In Chrome and Firefox every tail call still adds a frame to the stack.

A base case only helps if the argument is sure to reach it. Usually the argument shrinks with every call, so it gets there. Some functions have an argument that goes up and down. For some of them, nobody knows for certain whether they always stop.