The call stack: what happens when functions call functions
Follow a program through functions that call functions: a call pauses the line that made it, every call gets a frame with its own boxes on the call stack, only the top one runs, and Node’s stack trace is that pile, read downward to the call that handed over a bad value.
TypeScript
Fundamentals
The call stack: what happens when functions call functions. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson endOfDay called percentDone, and something
quiet happened that you did not have to think about. The computer
went into percentDone, worked out 67, and came back to the
middle of the very line it had left, with 67 in hand, and carried
on from there. It never got lost, and it never went back to the
wrong line. Keeping track of one call inside another is already a
small feat, and a real program has calls inside calls inside calls.
Your grandmother's drawer shows how it is done. You are following
the card for Sunday lunch, and step 1 says Make the pastry (see
the pastry card). You keep a finger on step 1, take out the
pastry card and lay it on top. The pastry card says Make the
filling (see the filling card), so a third card goes on top of
that one. When the filling is done, you take its card off, and
underneath, the pastry card is exactly where you left it. In this
lesson you meet the computer's pile of cards, the call stack.
By the end you will follow any program through its calls, say at
every line which calls are waiting and where each one comes back
to, and read Node's stack trace as that pile.
A call waits for its answer
Here is the end-of-day report again, with the score line given a
function of its own, scoreLine. It now takes three calls to
print one line: the file calls endOfDay, endOfDay calls
scoreLine, and scoreLine calls percentDone.
Look at line 10. console.log cannot print anything yet: what it
should print is the answer of scoreLine, and there is no answer
until scoreLine has run. So endOfDay stops in the middle of
line 10 and waits. scoreLine does the same on line 5, waiting for
percentDone. A call does not run beside the line that made it; it
pauses that line until the answer comes back, and the answer
then takes the call's place, as in lesson 5.1.
The calls and their answers, in order. Press Next to walk
through them, or let it play:
global
endOfDay
scoreLine
percentDone
1
global to endOfDay: endOfDay(done,left)
2
endOfDay to scoreLine: scoreLine(2,3)
3
scoreLine to percentDone: percentDone(2,3)
4
percentDone to scoreLine: 67
5
scoreLine to endOfDay: "2of3done(67%)"
6
endOfDay to global: undefined
Each call waits for its answer, and the answer goes back to it
All 6 steps shown.Step 1 of 6: global → endOfDay — endOfDay(done, left)Step 2 of 6: endOfDay → scoreLine — scoreLine(2, 3)Step 3 of 6: scoreLine → percentDone — percentDone(2, 3)Step 4 of 6: percentDone → scoreLine — 67Step 5 of 6: scoreLine → endOfDay — "2 of 3 done (67%)"Step 6 of 6: endOfDay → global — undefined
All 6 steps shown.
Every answer goes back to the one that asked, not to the file.
percentDone hands 67 to scoreLine, and does not even know that
endOfDay exists. And the last arrow is undefined: endOfDay is
a void function, and lesson 5.6 showed that a call of a void
function gives back undefined. After step 3, three calls are
under way at once: endOfDay waits on line 10, scoreLine waits
on line 5, and percentDone runs. That raises the question this
lesson answers: how does the computer remember where each waiting
call comes back to?
The call stack: a pile of frames
It keeps a pile, like the recipe cards. The pile is the call
stack: every call that has started and not yet finished, the
newest on top. Each card on it is a frame, and a frame holds
two things for one call: its own boxes (its parameters and the
boxes its lines make), and, while the call waits, the line it waits
on.
A call puts a new frame on top of the pile. Programmers say it is
pushed, the same word as tasks.push in lesson 4.1, which adds
to the end of a list. When the call ends, at a return or at its
closing brace, its frame comes off, which they call popping it,
and its answer goes to the frame now on top, which carries on from
the line it was waiting on. Only the top frame
runs; every frame under it waits. At the very bottom is global,
the file itself, the name the player has shown you since lesson
5.1.
Here is the end-of-day report, card by card. Press Next step
to follow it, or Play:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
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.
percentDonerunning line 1
part22
whole33
gives back 67gives back 67
scoreLinewaiting on line 5
done22
all33
percent6767
gives back "2 of 3 done (67%)"gives back "2 of 3 done (67%)"
The file runs line 12, a call of endOfDay. Only global, the
file itself, is on the pile.
Line 8.done = ["buy milk", "call mom"], left = ["pay rent"]. Inside endOfDay. global waits on line 12.
A card for endOfDay goes on top, holding its parameters. global
waits on line 12.
Line 9.all = 3. Inside endOfDay. global waits on line 12.
Line 9 makes all on endOfDay's own card: two done and one left
make 3.
Line 4.done = 2, all = 3. Inside endOfDay → scoreLine. endOfDay waits on line 10, global on line 12.
Line 10 calls scoreLine(2, 3). Its card has a done of its own,
the number 2, beside endOfDay's list.
Line 1.part = 2, whole = 3. Inside endOfDay → scoreLine → percentDone. scoreLine waits on line 5, endOfDay on line 10, global on line 12.
Line 5 calls percentDone(2, 3): a fourth card, the top of the
pile. scoreLine waits on line 5.
Line 2.Inside endOfDay → scoreLine → percentDone. scoreLine waits on line 5, endOfDay on line 10, global on line 12.
Only the top card runs. percentDone works out 67 and gives it
back.
Gives back 67
Line 5.percent = 67. Inside endOfDay → scoreLine. endOfDay waits on line 10, global on line 12.
The return takes percentDone's card off, part and whole with
it. 67 lands in scoreLine's percent, on line 5.
Line 6.Inside endOfDay → scoreLine. endOfDay waits on line 10, global on line 12.
scoreLine builds its line of text and gives it back.
Gives back "2 of 3 done (67%)"
Line 10.Inside endOfDay. global waits on line 12.
scoreLine's card comes off. Back on line 10, endOfDay prints
what it was given.
Prints 2 of 3 done (67%)
Line 12.
endOfDay ends, and its card comes off with its boxes. Back on line
12, with nothing left to run.
A call puts a card on the pile; a return takes it off
Step 7 is the one to watch. When percentDone returns, its frame
comes off the pile, and part and whole go with it. That is the
"fresh box each call" of lesson 5.1 seen from underneath: a call's
boxes live on its frame, a new call gets a new frame, and a
finished call's frame is gone. (The one exception is a box a
closure keeps, lesson 5.5: the arrow takes that box along.)
Now look at step 4. There are two boxes called done on the pile
at once: endOfDay's holds the list ["buy milk", "call mom"],
and scoreLine's holds the number 2. They never clash, because
they are on different frames, and a line only ever reads the frame
it runs on. Each function can name its parameters whatever fits its
own job, whatever names the function that calls it gave its own
boxes.
The Call stack column is the pile
Every Step player in this course has had a Call stack column.
It is the same pile, laid on its side: the bottom frame first, and a
› before every frame on top of it. Press Run, then press
Step and go to line 2:
It prints 2 of 3 done (67%). On line 2 the column says
global › endOfDay › scoreLine › percentDone: four frames, read
from the bottom up. On line 5, once percentDone has returned, it
is back to global › endOfDay › scoreLine. A call adds a name on
the right; a call that ends takes the rightmost one off.
A stack trace is the pile, printed
In lesson 1.5 you met Node's stack trace, the at lines under an
error: "a list of the places Node was in when it stopped, your own
line first". You skipped all but one of them. With functions, more
of those lines are yours, and now you can read them. Here is a
program that prints which task to start the day with. Its last line
hands it an empty list:
TypeScript accepts it, and Node stops on line 2 with
TypeError: Cannot read properties of undefined (reading 'slice'). To
see the whole stack trace, save it as plan.ts in
~/projects/taskkit and run it in your terminal (delete it
afterwards, so TaskKit's folder holds only TaskKit's files):
bash
node plan.ts
Node prints the line where it stopped with a ^ under it, then
these lines, from your own file; the node:internal lines after
them are Node's, and the last line is your Node version, as in
lesson 1.5:
Outputtext
TypeError: Cannot read properties of undefined (reading 'slice') at capitalize (/Users/ana/projects/taskkit/plan.ts:2:15) at firstTask (/Users/ana/projects/taskkit/plan.ts:5:10) at printPlan (/Users/ana/projects/taskkit/plan.ts:8:30) at Object.<anonymous> (/Users/ana/projects/taskkit/plan.ts:10:1)
TypeError: Cannot read properties of undefined (reading 'slice') at capitalize (C:\Users\ana\projects\taskkit\plan.ts:2:15) at firstTask (C:\Users\ana\projects\taskkit\plan.ts:5:10) at printPlan (C:\Users\ana\projects\taskkit\plan.ts:8:30) at Object.<anonymous> (C:\Users\ana\projects\taskkit\plan.ts:10:1)
TypeError: Cannot read properties of undefined (reading 'slice') at capitalize (/home/ana/projects/taskkit/plan.ts:2:15) at firstTask (/home/ana/projects/taskkit/plan.ts:5:10) at printPlan (/home/ana/projects/taskkit/plan.ts:8:30) at Object.<anonymous> (/home/ana/projects/taskkit/plan.ts:10:1)
On newer versions of Node the paths may start with file:///; the
line and column numbers stay the same.
Those four lines are the pile at the moment Node stopped, top frame
first, each with the line that frame was on:
at capitalize (plan.ts:2:15)
Where Node stopped: task holds undefined
at firstTask (plan.ts:5:10)
Where the bad value came from: tasks[0] of an empty list
at printPlan (plan.ts:8:30)
Waiting on line 8 for the first task
at Object.<anonymous> (plan.ts:10:1)
global, the file itself: line 10 called printPlan([])
Node prints the pile from the top: first, where it stopped
Object.<anonymous> is Node's name for the file's own frame, the
one the player calls global. The node:internal lines under it
are Node's own frames, which started your file.
The numbers after each file are a line and a column: plan.ts:5:10
is line 5, where firstTask waits on its call of capitalize.
Lesson 4.1 showed why the call goes wrong: tasks[0] of an empty
list is undefined, with no error, and TypeScript still types it
as a string. capitalize is handed undefined and stops on its
first use.
Predict before you run
Both functions print now, and so does the line that calls them.
Follow the pile in your head: who is on top, and where does each
call carry on once its answer comes back?
The first at line says where Node stopped, and it is natural to
go there and change that function. Often that is the wrong place.
Common mistake
Fixing the function on the first line of the stack trace
The trace starts at capitalize (plan.ts:2:15), so you open
capitalize and make it cope with nothing:
plan.tsts
function capitalize(task: string): string { if (task === undefined) { return ""; } return task.slice(0, 1).toUpperCase() + task.slice(1);}
The crash is gone, and the program now prints Start with: , with
nothing after it: a plan that quietly says nothing. And task is
typed string, so to the next person the check reads as nonsense:
how could a string be undefined? capitalize was never wrong.
It was handed a value it should not have been.
TypeError: Cannot read properties of undefined (reading 'slice')
The fix
Read on down the trace to the call that handed the value over:
firstTask, on line 5, passed tasks[0] of an empty list. Decide
there what an empty list means, and leave capitalize as it was:
When a TypeError says a value is undefined inside a function,
the function is usually the victim, not the culprit. Read the at
lines downward, and at each one ask what that call handed to the
frame above it. The first call that handed over something it should
not have is where the fix goes.
TypeError: Cannot read properties of undefined (reading 'toUpperCase') at shout (shout.ts:2:15) at lastTask (shout.ts:5:10) at Object.<anonymous> (shout.ts:7:13)
Exercise · Fix the error
Fix it where the value came from
This program should print today's first task, Buy milk, but it
stops with the stack trace below. Read it downward to where the bad
value is handed over, and fix that line, changing nothing in the
functions.
Its stack trace, with the folders left outtext
TypeError: Cannot read properties of undefined (reading 'slice') at capitalize (first.ts:2:15) at firstTask (first.ts:5:10) at Object.<anonymous> (first.ts:9:13)
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does a call do to the line that made it?
Check yourself
Which frame runs at any moment?
Check yourself
The stack trace starts with capitalize. Where is the fix?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
The call stack: what happens when functions call functions
What things are
Word
What it means
Call stack
Every call under way, the newest on top
Frame
One call's card: its own boxes and the line it waits on
Push
A call puts a new frame on top
Pop
The call ends (return, or its closing brace); its frame comes off
global
The file's own frame, under every call
Stack trace
The pile when Node stopped, top frame first
Object.<anonymous>
Node's name for the file's frame in a trace
Code
Write or see
To
scoreLine(2, 3)
Push a frame; the caller waits on this line
return answer;
End the call; answer takes the call's place
global › endOfDay › scoreLine
The pile on its side, bottom first
at firstTask (plan.ts:5:10)
One frame: its function, line and column
console.trace("label");
Print the pile now, without stopping
Rules
Rule
What it means
Only the top runs
Every frame under it waits on its own line
A caller waits
It pauses mid-line until the answer comes back
Own boxes
Each frame holds its call's boxes; they go when it pops
Same name, two frames
Two boxes, which never clash
Read a trace downward
The top line is where it stopped
Fix at the source
Change the call that handed the bad value over
Where to go next
You can now follow a program through calls inside calls. You know
that a call pauses the line that made it, that each call gets a
frame of its own on the call stack, that only the top frame runs,
and that a stack trace is that pile, printed at the moment Node
stopped, to be read downward to where the bad value came from.
Next is Recursion: a function that calls itself. Every frame
in this lesson belonged to a different function. There you see
what happens when a function calls itself, so the pile holds
several frames of the same function, and why such a pile has to
stop growing somewhere.
Before you move on, look at TaskKit's pile. In index.ts in
~/projects/taskkit, add console.trace("percentFull"); as the
first line inside percentFull. console.trace prints the pile at
that moment, as a stack trace, without stopping anything. Run:
bash
node index.ts add a b c
Just before List 60% full, under Trace: percentFull, you see
these lines (shown here with the folders left out; your line
numbers depend on where the lines sit in your file):
Outputtext
Trace: percentFull at percentFull (index.ts:5:11) at printSummary (index.ts:35:19) at Object.<anonymous> (index.ts:82:1)
percentFull on top, printSummary under it, then the file's own
frame, followed by Node's node:internal lines. Then delete the
line again.