Read a loop you cannot run by being the computer for a minute: write a trace table with a column for every box and a row for every turn, starting from what each box holds before the loop. Trace the check too, since it runs once more than the body, and use the table to find the exact turn where a loop goes wrong, such as one that reads past the end of its list and prints NaN. Closes Module 4 with a one-page cheat sheet of the whole module.
TypeScript
Fundamentals
Reading code: tracing a loop by hand. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
A friend who started this course when you did sends you a message
on the bus. It is eight lines of code and one question: "I have
three tasks, 25, 15 and 10 minutes. Why does it say
4 tasks fit in an hour, NaN minutes?" You are on your phone. There
is no editor, no Run button and no player to step through it.
All you have is the code and your own head, and by the third turn
of the loop your head has lost count.
Think of a card game where somebody keeps the score sheet. Nobody
carries the score in their head: after every round, a new row, one
column for every player. And when the final score looks wrong, you
go down the sheet and find the round where someone added wrong. By
the end of this lesson you keep that sheet for a loop: a row for
every turn, a column for every box. You will say what a loop prints
before you run it, and find the exact turn where your friend's loop
goes wrong.
Being the computer for a minute
All through this module the player has done the remembering for
you: press Step, and it shows what every box holds after every
line. Tracing is doing that yourself. You read the code the way
the computer runs it, one line at a time, top to bottom, and write
down what every box holds as it changes. Nothing runs. You are the
computer.
Most code you will ever read, you will not run first: a friend's
message, an example in the documentation, a colleague's change you
are asked to look at, a loop you suspect would never end. And when
code you can run prints the wrong thing, running it again only
shows the same wrong answer. Tracing shows where it came from.
A program without loops is easy to follow in your head: every line
runs once. A loop is not. The same three lines run again and again,
each time with different values in the boxes, and by the third turn
you are no longer sure whether a box held 40 or 70. So write it
down: on paper, or in a text file next to the code. It takes a
minute, and paper does not forget.
A trace table: a row for every turn
The sheet you write is a trace table. It has a column for every
box the loop changes, and a column for what it prints. It has a row
for every turn, filled in once that turn is over, with two more
rows around them:
The start row: what each box holds before the loop begins.
A row for every turn: what each box holds once that turn's
lines have run.
The after row: what is left when the loop is over, and what
the lines after it print.
Here is the running total from lesson 4.5, the loop you are going
to trace:
ts
const minutes = [25, 15, 30, 10];let total = 0;for (const minute of minutes) { total += minute;}console.log(total);
Each turn begins with the loop's own question. A for...of asks
whether there is another item; if there is, it puts it in minute
and runs the body. Then you write down what the body did. Press
Next step to fill the table one cell at a time, or let it play:
Turn
minute
total
Prints
Turn: StartStartStart
total: 000
Turn: 111
minute: 252525
total: 252525
Turn: 222
minute: 151515
total: 404040
Turn: 333
minute: 303030
total: 707070
Turn: 444
minute: 101010
total: 808080
Turn: AfterAfterAfter
Prints: 808080
Time
Before the loop: only the boxes made above it exist.
let total = 0; puts 0 in the box.
for...of asks for an item, and there is one: turn 1.
minute holds the first item.
total += minute: 0 + 25.
Another item is left: turn 2.
minute holds the second item.
total += minute: 25 + 15.
Another item is left: turn 3.
minute holds the third item.
total += minute: 40 + 30.
One item is left: turn 4.
minute holds the last item.
total += minute: 70 + 10.
No item is left, so the loop ends.
console.log(total) prints 80.
A row for every turn: what each box holds once the turn is over
All 16 steps shown.Step 1 of 16: Turn: StartStep 2 of 16: total: 0Step 3 of 16: Turn: 1Step 4 of 16: minute: 25Step 5 of 16: total: 25Step 6 of 16: Turn: 2Step 7 of 16: minute: 15Step 8 of 16: total: 40Step 9 of 16: Turn: 3Step 10 of 16: minute: 30Step 11 of 16: total: 70Step 12 of 16: Turn: 4Step 13 of 16: minute: 10Step 14 of 16: total: 80Step 15 of 16: Turn: AfterStep 16 of 16: Prints: 80
All 16 steps shown.
On a phone the table stands the way you write it on paper, one row
under another. On a wide screen it lies on its side, and each turn
is a column; the cells are the same. Notice two empty cells.
minute has nothing in the start row, because the loop makes it,
and nothing after, because it belongs to the loop and is gone once
the loop ends, as lesson 4.2 showed.
The rule that keeps a trace honest: every new value is worked out
from the row above, never from what you expect the answer to be.
Turn 3's total is turn 2's total, 40, plus turn 3's minute,
30. Now check your table against the computer. Press Step and
compare each turn with its row, or Run to see the last line:
total.tsts
const minutes = [25, 15, 30, 10];let total = 0;for (const minute of minutes) { total += minute;}console.log(total);
The player stops on total += minute; four times, with the same
values your table has in its four rows, and the program prints 80.
The player only ever shows what the boxes hold at this moment; your
table keeps every turn, and that is what lets you look back.
Trace the condition too
A for...of asks its question out of sight. A counting for and a
while write theirs in the code, as a condition, and it belongs in
the table as a column of its own, because it decides whether the next
turn happens at all. Take the numbered list from lesson 4.2:
As lesson 4.2 showed, the condition is asked before every turn, and
a false answer ends the loop. Its trace table has a row for every
time it is asked:
i < tasks.lengthThe body printsi = 0
true
0 < 3
1.buymilk
Turn 1
i = 1
true
1 < 3
2.callmom
Turn 2
i = 2
true
2 < 3
3.payrent
Turn 3
i = 3
false
3 < 3
Nothing
The loop ends
Three turns, the condition asked four times: false ends the loop
Three turns, four times the condition is asked. It is always asked
once more than the body runs, because the last answer, the false one,
is what stops the loop, and the body does not run after it. That last
row is the one people leave out of their tables, and it is exactly the
row where the <= of lesson 4.2 goes wrong: with i <= tasks.length,
the condition at i = 3 says true, and a fourth turn reads
tasks[3].
So when you trace a for or a while, write the condition first in
every row, and do not stop until you have written a false one.
Find the turn where it goes wrong
Now your friend's message. Here is the code they sent:
ts
const minutes = [25, 15, 10];let used = 0;let count = 0;while (used < 60) { used += minutes[count]; count++;}console.log(`${count} tasks fit in an hour, ${used} minutes`);
Trace it. The columns are the condition, used < 60, and the box it
reads, used. count needs no column, because it follows the
turns: while turn 3 runs it is 2, so turn 3 reads minutes[2], and
count++ makes it 3 by the end of the turn. After turn 4 it is 4,
which is what the program prints. Write the condition first in every
row, then the body:
used < 60usedStart
—
Not asked yet
0
The start value
Turn 1
true
0 < 60
25
0 + 25
Turn 2
true
25 < 60
40
25 + 15
Turn 3
true
40 < 60
50
40 + 10
Turn 4
true
50 < 60
NaN
50 + undefined
After
false
NaN < 60
NaN
Printed
Turn 4 reads past the end of the list, and used becomes NaN
The first three turns are what your friend expected. Turn 4 is where
it goes wrong. After three tasks used is 50, and 50 < 60 is still
true, so the loop takes a fourth turn. count is 3, and minutes[3]
is past the end of a list of three: as lesson 4.1 showed, that gives
undefined, with no error. Adding undefined to a number gives
NaN, short for not a number, the way Number(undefined) did in
lesson 3.3. Then NaN < 60 is false, the loop ends, and the program
prints a count of 4 and a used of NaN. Every part of the message
is explained by one row.
The row also says what is missing: the loop never asks whether
there is a next task. Lesson 4.2 wrote this loop with two questions
in its condition, and the trace shows why both are needed.
Bad — asks only whether there is
time left, so it reads one task past the end.
ts
const minutes = [25, 15, 10];let used = 0;let count = 0;while (used < 60) { used += minutes[count]; count++;}console.log(`${count} tasks fit in an hour, ${used} minutes`);
Good — asks first whether there is
a next task, then whether it fits.
ts
const minutes = [25, 15, 10];let used = 0;let count = 0;while (count < minutes.length && used + minutes[count] <= 60) { used += minutes[count]; count++;}console.log(`${count} tasks fit in an hour, ${used} minutes`);
The first prints 4 tasks fit in an hour, NaN minutes, and the
second 3 tasks fit in an hour, 50 minutes. TypeScript accepts both
without a word, because square brackets trust the list, so a trace
was the only way to find the bug without running the code. Run them
anyway: comparing your table with the real output is how tracing
gets fast.
Predict before you run
This loop keeps the longest task it has seen so far, and says so
each time it finds a longer one. Trace it, with a column for
minute, one for longest and one for what it prints, then
answer.
The start row is the other row people skip, in their tables and in
their code. A running total looks like it only needs filling inside the
loop, so the line that makes it gets no value.
Common mistake
Making a running total with no start value
You want to add up today's minutes, and the loop does the adding,
so you make the box and leave it empty:
total.tsts
const minutes = [25, 15, 30, 10];let total;for (const minute of minutes) { total += minute;}console.log(total);
npx tsc --noEmit--types node total.ts (tsc is the TypeScript
compiler, which npx starts) refuses it before it runs:
Outputtext
total.ts:4:3 - error TS18048: 'total' is possibly 'undefined'.4 total += minute; ~~~~~Found 1 error in total.ts:4
TS18048 is the error's code; TS is for TypeScript.
'total' is possibly 'undefined'.
The fix
Give the box the value the total starts from, before the loop:
total.tsts
const minutes = [25, 15, 30, 10];let total = 0;for (const minute of minutes) { total += minute;}console.log(total);
Try to write the start row for the first version and you find the
hole yourself: a box made without a value holds undefined, as
lesson 3.3 showed, so turn 1 is undefined + 25, which is NaN,
and every row after it is NaN too. Run it with Node anyway and it
prints NaN. So write the start row first, every time. If you cannot fill
one of its cells, the code cannot either.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Trace each one on paper or in a text file before you answer. Press
Check when you think you have it; if you are stuck, the hints
come one at a time.
Exercise · Read the code
Read the total after turn 2
Once the second turn of this loop is over, what is in total?
ts
const minutes = [10, 20, 30];let total = 5;for (const minute of minutes) { total += minute;}console.log(total);
Exercise · Predict the result
Count the conditions asked
This loop prints every second task: i += 2 adds 2 to i after
every turn, instead of 1. How many times is the condition
i < tasks.length asked?
ts
const tasks = [ "buy milk", "call mom", "pay rent", "call dad", "water plants",];for (let i = 0; i < tasks.length; i += 2) { console.log(tasks[i]);}
Exercise · Fix the error
Give the shortest a real start
This program should print 10, the shortest task, but it prints
0. Trace it to find the row where it goes wrong, then fix it
without changing the loop.
Loading the editor…
Exercise · Write the code
Write the loop from its trace
Someone traced a loop and lost the code. Here is their trace table.
Write the code it came from, with the box letters, so that it
prints 28.
Row
task
letters
Start
—
0
Turn 1
"buy milk"
8
Turn 2
"call dad"
16
Turn 3
"water plants"
28
After
—
28, printed
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does one row of a trace table hold?
Check yourself
A trace shows used turning NaN in turn 4. Where do you look?
Check yourself
Why write the start row before the first turn?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Reading code: tracing a loop by hand
What things are
Word
What it means
Tracing
Running code by hand, writing down every box
Trace table
A row for every turn, a column for every box
Start row
What each box holds before the loop begins
After row
What is left, and printed, once the loop ends
Condition
The question a loop asks before every turn
How to trace a loop
Step
What you do
Columns
One per box the loop changes, one for what it prints
Start row
Write each box's value before the loop
The condition
Write it first in every row; false ends the loop
The body
Run its lines in order, from the row above
The row
Write what each box holds once the turn is over
Rules
Rule
What it means
Asked = turns + 1
The last answer is false and runs nothing
From the row above
Never from the answer you expect
Past the end
The turn that reads it: 50 + undefined is NaN
No start value
let total; holds undefined: TS18048
First wrong row
Where the bug is; compare with what you expected
Module 4 on one page
Cheat sheet
Module 4: Arrays and Loops
Arrays and the T[] type
Write
To
string[]
The type of a list of strings
tasks[0]
Read the first item; indexes count from 0
tasks.length
Count the items
tasks.at(-1)
The last item, or undefined
tasks.push("pay rent")
Add an item at the end
tasks[3] past the end
undefined, with no error
for, for...of, and while
Write
To
for (const task of tasks)
Run the body once per item
for (let i = 0; i < tasks.length; i++)
Count through every index
while (used < 60) { … }
Repeat while the condition is true
i < tasks.length
Never <=: it takes one turn too many
map, filter, find, some, and every
Write
To
.map((task) => …)
Make a new list of the rule's answers
.filter((task) => …)
Keep the items the rule says true to
.find((task) => …)
Get the first item that passes, or undefined
.some(…) / .every(…)
Ask whether at least one, or all, pass
Sorting and its pitfalls
Write
To
.sort((a, b) => a - b)
Sort numbers, smallest first
a.localeCompare(b)
Compare two words as a dictionary does
.toSorted(…)
Get a new list in order; the old one stays
Numbers need a rule
With none, 10 comes before 5
reduce
Write
To
.reduce(rule, 0)
Fold the list into one value, starting at 0
(total, minute) => …
The rule: the total so far and the next item
Always give a start
Without one, an empty list is a TypeError
Simple tuples
Write
To
[string, number]
Two places: a string, then a number
entry[0], entry[1]
Read each place, counted from 0
[string, number][]
A list of such pairs
Write the type
Without it, a list: (string | number)[]
Reading code: tracing a loop by hand
Step
What you do
A trace table
A row for every turn, a column for every box
The start row
Each box's value before the loop
The condition first
Asked = turns + 1; the false one ends it
The first wrong row
Look there for the bug
Where to go next
You can now trace a loop by hand: a column for every box, a start
row, a row for every turn worked out from the one above, and a
condition written first until it says false. You can say what a loop prints
before you run it, and find the turn where one goes wrong. That
closes Module 4: lists, the loops that walk them, the methods that
do the walking for you, and a way to read all of them.
Next is Declaring functions: parameter and return types, the
first lesson of Module 5. So far your code has run top to bottom in
one piece. There you start giving a few lines a name, so you can
run them again from anywhere, and say what goes in and what comes
out.
Before you move on, open TaskKit's index.ts and trace its add
loop by hand for
node index.ts add "buy milk" " " "call mom": a row for every time
i < process.argv.length is asked, with i, the tidy task and the
line it prints, down to the false one. Then run the command
and compare every line with your table.