Recursion: a function that calls itself (a gentle first look)
Write a function that calls itself: a base case it answers alone, a recursive case with a smaller job, a card of its own on the call stack for every call, answers coming back from the smallest call, and the RangeError a missing base case leaves behind.
Fundamentals
TypeScript
Recursion: a function that calls itself (a gentle first look). Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson every card on the call stack belonged to a
different function: endOfDay called scoreLine, and scoreLine
called percentDone. Nothing stops a function from calling itself,
though, and some jobs are easiest to describe exactly that way.
You are in a queue at the post office, so long that it bends round a
corner, and you want to know your place in it. You cannot see the
front. So you tap the person ahead and ask, "What number are you?"
They cannot see the front either, so they ask the person ahead of
them, and the question travels up the queue. Only the person at the
very front can answer without asking anyone: "I'm first." Then the
answer travels back: "then I'm 2", "then I'm 3", until it reaches
you. Nobody counted the queue. Each person asked the same question
one place closer to the front, and the front answered it alone. By
the end of this lesson you will write a function that works like
that, say where it stops, follow its calls on the call stack card by
card, and recognise the error Node prints when such a function never
stops.
A function that calls itself
Take the countdown before a break: 3, 2, 1, Go! Counting down from 3
is saying 3, then counting down from 2. Counting down from 2 is
saying 2, then counting down from 1. Counting down from 1 is saying
1, then counting down from 0. And counting down from 0 is the
one countdown with nothing left to count: you just say Go!
Press Next to walk through the calls, or let it play:
countdown(3)
Prints 3, then hands the rest to countdown(2)
countdown(2)
Prints 2, then hands the rest to countdown(1)
countdown(1)
Prints 1, then hands the rest to countdown(0)
countdown(0)
Prints Go! and calls nothing: the stop
Each call does one step and leaves a smaller countdown
All 4 steps shown.Step 1 of 4: countdown(3)Step 2 of 4: countdown(2)Step 3 of 4: countdown(1)Step 4 of 4: countdown(0)
All 4 steps shown.
In TypeScript, "hands the rest to" is a call of the function's own
name, with a smaller number:
It prints 3, 2, 1 and Go!. Line 7 is the new thing:
countdown calls countdown. A function that calls itself is
recursive, the call on line 7 is a recursive call, and
solving a job this way, by handing a smaller copy of it to the same
function, is recursion. TypeScript has nothing against it. The
name countdown is in scope inside its own body, as lesson 5.5
would predict, and the function already exists by the time line 7
runs.
Two parts: the stop and the smaller step
Every recursive function has the same two parts, and it needs both.
The base case is the call the function answers alone, without
calling itself. In countdown it is n === 0: print Go! and end
the call with return;, as in lesson 5.6. It is the person at the
front of the queue. Without it, nothing would ever stop the
countdown.
The recursive case is every other call: do one step, then call
the function again with a job a little smaller, here n - 1.
"Smaller" means closer to the base case. Each call takes one step
towards it, so a countdown from 3, or from 300, reaches 0 and stops.
Every call gets its own card
Lesson 5.8 drew the call stack as a pile of cards, called frames,
one per call under way. A recursive function puts several cards for the same
function on the pile at once, and each one holds its own n. Press
Next step to follow it, or Play:
Step 8 is the one to watch: four cards called countdown, holding
3, 2, 1 and 0. They never mix, for the reason lesson 5.8 gave for
two boxes called done: every call gets fresh boxes on its own
card, and a line only reads the card it runs on. The pile grows by
one card per call until the base case, and then shrinks by one card
per return. It cannot shrink any sooner, because a card comes off
only when its call ends, and each call ends only after the call it
made.
Answers come back from the smallest call
countdown only prints. A recursive function can also give an
answer back, and then the answers are worked out on the way back
down the pile.
In lesson 5.3, total(25, 15, 30) added up the minutes of three
tasks with reduce. Here is the same sum said the recursive way:
the total of a list is its first item plus the total of the rest.
The total of an empty list is 0, with nothing to add, and that is
the base case.
A list has a slice too, and it works like the string slice of
lesson 2.4: minutes.slice(1) is a new list of every item from index
1 on, which is everything but the first: [25, 15, 30].slice(1) is
[15, 30]. Each call hands on a list one item shorter, so the calls
reach the empty list and stop. Run it:
It prints 70. On the way up the pile nothing gets added: line 5
needs the total of the rest before it has anything to add 25 to, so
each call waits on line 5, as scoreLine waited on percentDone in
lesson 5.8. Only the empty list answers at once. Then the answers come
back, and each call adds its own first item to the answer it gets.
Press Next to follow them, or let it play:
totalMinutes([]) gives 0
The stop: an empty list adds up to 0, with no call
totalMinutes([30]) gives 30
30 plus the 0 that came back from []
totalMinutes([15, 30]) gives 45
15 plus the 30 that came back from [30]
totalMinutes([25, 15, 30]) gives 70
25 plus the 45 that came back from [15, 30]
The answers come back from the smallest list to the whole one
All 4 steps shown.Step 1 of 4: totalMinutes([]) gives 0Step 2 of 4: totalMinutes([30]) gives 30Step 3 of 4: totalMinutes([15, 30]) gives 45Step 4 of 4: totalMinutes([25, 15, 30]) gives 70
All 4 steps shown.
The base case answers first and the first call answers last. That
is the queue at the post office again: the question went up to the
front, and the answer came back, one person at a time, to you.
A loop or a function that calls itself
You could write the countdown with the while loop of lesson 4.2:
Both versions print the same four lines. For a countdown or a sum,
the loop is the plainer choice: one box, one condition, and no pile
of cards. When a loop says it as clearly, use the loop.
Recursion earns its place on a different shape of job: something that
holds smaller things of its own kind. A folder holds files and other
folders, and those hold folders of their own. To count every file in
it, you count the files right there, then count each folder inside it
the same way, and a folder with no folders inside is the base case.
Menus and comment threads with replies have that shape too.
For now, what matters is reading a recursive function and following
its pile.
Predict before you run
This countdown prints after its recursive call instead of before
it. Follow the pile in your head: which call prints first?
Predict
What is the first line this program prints?
The common mistake: no base case
The recursive case is the interesting part to write, and the base
case is the easy one to forget.
Common mistake
A recursive function with no base case
You write the rule just as you would say it, the first item plus the
total of the rest:
TypeScript accepts it, because every type is right. But the list gets
shorter, reaches [], and the calls go on: [].slice(1) is []
again, so every call makes another one just like it. The pile only
grows, until Node has no room left for another card. RangeError is
JavaScript's word for a value past its allowed limit: here, the size
of the pile. In your own terminal, node minutes.ts prints the file
and the line it stopped on, with a ^ under the spot, then this:
Under the at lines, the last line shows your Node version. On newer
versions of Node the paths start with file:///; the line and
column numbers stay the same.
Those at lines are the stack trace of lesson 5.8: read them as the
pile, from the top:
at Array.slice (<anonymous>)
Where Node ran out of room, making one more shorter list
at totalMinutes (minutes.ts:2:44)
The newest card: line 2, column 44, making minutes.slice(1)
at totalMinutes (minutes.ts:2:23)
The card under it, waiting on its call of totalMinutes, and
seven more like it
… thousands more cards
Maximum call stack size exceeded almost always means a recursive
function that never reached its base case. Programmers call it a
stack overflow: the pile grew past the room it has. A stack trace
whose at lines nearly all name the same function on the same line is
the sign. Then look for two things: is there a base case at all, and
does every call really move closer to it?
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one runs in your browser. Press Check when you think you
have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What makes a recursive function stop?
Check yourself
In totalMinutes([25, 15, 30]), which call answers first?
Check yourself
What does Maximum call stack size exceeded usually mean?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Recursion: a function that calls itself (a gentle first look)
What things are
Word
What it means
Recursion
Handing a smaller copy of a job to the same function
Recursive function
A function that calls itself
Recursive call
Its call of itself, with a smaller job
Base case
The call it answers alone, without calling itself
Recursive case
One step, then a call with a smaller job
Stack overflow
A pile with no room left for another card
Code
Write
To
if (n === 0) { … }
Check for the base case first
countdown(n - 1)
Call itself with a smaller job
return 0;
Answer the base case alone
minutes.slice(1)
Every item but the first, as a new list
minutes[0] + …
Add one item to the answer for the rest
Rules
Rule
What it means
Two parts
A base case and a recursive case
Closer every call
Each call's job is nearer the base case
Own card, own boxes
Every call has its own n, even of one function
Answers come back
The base case answers first, the first call last
Print before or after
Before the call: 3 2 1; after it: 1 2 3
RangeError
Maximum call stack size exceeded: no stop reached
Where to go next
You can now read and write a recursive function: a base case it
answers alone, a recursive case that calls it again with a smaller
job, and a pile of cards, one per call, that grows to the base case
and shrinks as the answers come back. You also know the error a
missing base case leaves behind, and how to read its stack trace.
Next is The debugger: stepping through a function. So far the
page's player has stepped through code for you. There you pause your
own program on a line of your choosing and look at its boxes and its
call stack yourself.
Before you move on, make a stack overflow in your own terminal. In
~/projects/taskkit, create minutes.ts with totalMinutes from
this lesson and run node minutes.ts: it prints 70. Delete the
three lines of the base case, run it again, and read the at lines:
the same function, again and again, under one Array.slice. Then put
the base case back.
Never printed: Node shows only the top ten lines
The top of a pile with no stop: the same card, over and over
RangeError: Maximum call stack size exceeded
The fix
Give it a base case: an empty list adds up to 0. Put it first, above
the recursive call:
minutes.tsts
function totalMinutes(minutes: number[]): number { if (minutes.length === 0) { return 0; } return minutes[0] + totalMinutes(minutes.slice(1));}console.log(totalMinutes([25, 15, 30]));
It prints 70.
Loop or recursion
A loop when it says it as clearly
Exercise · Read the code
Count the cards
countdown(4) runs. At the moment the pile is at its tallest, how
many cards for countdown are on it?
ts
function countdown(n: number): void { if (n === 0) { console.log("Go!"); return; } console.log(n); countdown(n - 1);}countdown(4);
Exercise · Predict the result
Follow the answers back
What does this program print?
ts
function steps(n: number): string { if (n === 0) { return "Go"; } return `${n} ${steps(n - 1)}`;}console.log(steps(3));
countdown.tsts
function countdown(n: number): void { if (n === 0) { console.log("Go!"); return; } console.log(n); countdown(n - 1);}countdown(3);
minutes.tsts
function totalMinutes(minutes: number[]): number { if (minutes.length === 0) { return 0; } return minutes[0] + totalMinutes(minutes.slice(1));}console.log(totalMinutes([25, 15, 30]));
countdown-loop.tsts
let n = 3;while (n > 0) { console.log(n); n = n - 1;}console.log("Go!");
ts
function countUp(n: number): void { if (n === 0) { return; } countUp(n - 1); console.log(n);}countUp(3);
minutes.tsts
function totalMinutes(minutes: number[]): number { return minutes[0] + totalMinutes(minutes.slice(1));}console.log(totalMinutes([25, 15, 30]));
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
ts
function countdown(n: number): void { if (n === 0) { console.log("Go!"); return; } console.log(n); countdown(n - 1);}countdown(3);
Call stackThe calls under way, the newest on top. Each call has its own boxes; the ones below wait on the line that called. A return takes the top one off.
countdownrunning line 1
n00
countdownwaiting on line 7
n11
countdownwaiting on line 7
n22
countdownwaiting on line 7
n33
globalwaiting on line 9running line 9
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 9.
The file runs line 9, a call of countdown. Only global is on
the pile.
Line 1.n = 3. Inside countdown. global waits on line 9.
A card for countdown goes on top, holding n, which is 3.
global waits on line 9.
Line 6.Inside countdown. global waits on line 9.
3 is not 0, so the if is skipped, and line 6 prints 3.
Prints 3
Line 1.n = 2. Inside countdown → countdown. countdown waits on line 7, global on line 9.
Line 7 calls countdown(2): a second card of the same function,
with an n of its own, 2.
Line 6.Inside countdown → countdown. countdown waits on line 7, global on line 9.
2 is not 0 either: line 6 prints 2.
Prints 2
Line 1.n = 1. Inside countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, global on line 9.
Line 7 calls countdown(1): a third card, and its n is 1.
Line 6.Inside countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, global on line 9.
1 is not 0: line 6 prints 1.
Prints 1
Line 1.n = 0. Inside countdown → countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, countdown on line 7, global on line 9.
Line 7 calls countdown(0): a fourth card, the top of the pile.
Line 3.Inside countdown → countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, countdown on line 7, global on line 9.
n is 0 at last: the if is the stop, and line 3 prints Go!.
Prints Go!
Every call gets a card of its own, with its own n
Outputtext
RangeError: Maximum call stack size exceeded at Array.slice (<anonymous>) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:44) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/Users/ana/projects/taskkit/minutes.ts:2:23)
RangeError: Maximum call stack size exceeded at Array.slice (<anonymous>) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:44) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23) at totalMinutes (C:\Users\ana\projects\taskkit\minutes.ts:2:23)
RangeError: Maximum call stack size exceeded at Array.slice (<anonymous>) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:44) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23) at totalMinutes (/home/ana/projects/taskkit/minutes.ts:2:23)
Exercise · Fix the error
A base case the empty list never meets
This totalMinutes stops on a list of one item. It adds up
[25, 15, 30] correctly, but totalMinutes([]) never stops and
ends in RangeError: Maximum call stack size exceeded. Change the
base case so that an empty list gives 0. The program should then
print 70 and 0.
Loading the editor…
Exercise · Write the code
Count the tasks by calling itself
Write countTasks so that it calls itself, the way totalMinutes
does: an empty list has 0 tasks, and any other list has one task
plus the tasks in the rest of it. The program should print 3.
Loading the editor…
Line 4.Inside countdown → countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, countdown on line 7, global on line 9.
return; ends this call. It calls nothing, so the pile stops
growing.
Line 7.Inside countdown → countdown → countdown. countdown waits on line 7, countdown on line 7, global on line 9.
The top card comes off. The card with n = 1 was waiting on line
7, its last line, so it ends too.
Line 7.Inside countdown → countdown. countdown waits on line 7, global on line 9.
Its card comes off. The card with n = 2 is on top again, on its
last line, and ends.
Line 7.Inside countdown. global waits on line 9.
Its card comes off. The card with n = 3, the first one, is on
top again, and ends.
Line 9.
The first card comes off. Back on line 9, with nothing left to
run.