Debugging strategies: console, breakpoints, isolating the problem
Find where a bug with no error message starts: make it happen every time, then halve the lines it can be on with logs that show everything until one line is left. Stop on the one turn of a loop that matters with a conditional breakpoint, fix the bug where it starts rather than where it shows, and keep it fixed with a test.
TypeScript
Fundamentals
Debugging strategies: `console`, breakpoints, isolating the problem. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson unknown made TypeScript find a mistake before
anything ran. This lesson is about the mistakes no check can see. A
friend keeps their to-do list as lines of text, with an x in front
of each task that is done, and your five-line program counts what is
left. It says Left: 3. Your friend counts on their fingers: two. It
is a bug like lesson 5.10's 150%, a wrong answer with no error, and
this time you have no idea which line to put a breakpoint on.
Think of the game "higher or lower": someone picks a number from 1
to 100, and you guess. Nobody wins it by guessing 1, then 2, then 3.
You say 50, hear "lower", say 25, and every answer throws away half
of the numbers left. Finding a bug works the same way. By the end of
this lesson you will find the line where such a bug starts in a few
looks, with console.log or a breakpoint, fix it on that line, and
know how to keep it fixed.
First, make it happen every time
A bug you cannot make happen again is a bug you cannot check a fix
for. So before you look for anything, pin down three things: the
exact input, what you expected, and what you got. Here they are for
your friend's list. The input is in the code; run it:
The third line of the list is two spaces: your friend left a line
blank but touched the space bar. Line 2 trims every title, line 3
drops the blank ones, line 4 keeps the tasks without an x, and
line 5 counts them. Expected: Left: 2, for "pay rent" and "water
plants". Got: Left: 3. Write those two down; they are how you will
know you are done.
This is a quiet bug: the program runs to the end and gives a
wrong answer, with no error. TypeScript cannot catch it, because a
clean check means every value fits its type, nothing more (lesson
8.2). Every box here holds a list of string, just not the right
strings.
Halve the search
A quiet bug starts on one line and shows on a later one. Line 5
printed the wrong number, but line 5 only counts what it was given.
Somewhere above it, a box got a wrong value, and every line after it
passed that value on. So you look for the first box that holds a
wrong value, as with lesson 4.7's first wrong row in a trace table:
every box before it is right, and the line that fills it is the bug.
What is new is how fast you get there: halving, the way you play
higher or lower. Line 1 is the input you wrote down, so the lines
that can hold the bug are 2 to 4. Print the box made in the middle
of them with a log, a console.log you add only to look. Then
one rule decides:
The box is right: every line up to it did its job. The bug is
below.
The box is wrong: the bug is on the line that made it, or
above.
Either way, half the lines it can be on are gone. Each log and run
is one look. Do it again in the half that is left, until one line
remains. Press Next step to walk through the search, or let it
play:
You
Node
Bugison
You: run today.tsruntoday.tsruntoday.ts
Node: Left: 3Left:3Left:3
Bug is on: lines 2–4lines2–4lines2–4
You: log after line 3logafterline3logafterline3
Node: kept has ''kepthas''kepthas''
Bug is on: line 2 or 3line2or3line2or3
You: log after line 2logafterline2logafterline2
Node: titles is righttitlesisrighttitlesisright
Bug is on: line 3line3line3
Time
You run the file. You expect Left: 2.
One too many. Nothing crashed, and nothing says where.
Lines 2 to 4 work the count out, so any of them.
Halfway down lines 2 to 4: you print kept, and run again.
Wrong already: the blank line should be gone by now.
kept is made on line 3 from line 2's box.
Halfway down lines 2 and 3: you print titles, and run again.
'' belongs here: line 3 is the one meant to drop it.
Right before it, wrong after it: line 3 it is.
Each log in the middle halves the lines the bug can be on
All 9 steps shown.Step 1 of 9: You: run today.tsStep 2 of 9: Node: Left: 3Step 3 of 9: Bug is on: lines 2–4Step 4 of 9: You: log after line 3Step 5 of 9: Node: kept has ''Step 6 of 9: Bug is on: line 2 or 3Step 7 of 9: You: log after line 2Step 8 of 9: Node: titles is rightStep 9 of 9: Bug is on: line 3
All 9 steps shown.
Here are both looks in one file. Each console.log goes right under
the line whose box it prints. Run it, and compare with the figure:
So the bug is the filter that makes kept. Read it now that you
know where to look: it drops " ", one space. But trimming two
spaces leaves the empty string, "", so after trim a blank line is
never a space. Change " " to "", delete the two logs, and run it:
Left: 2, what you wrote down. In five lines you could have read
every line and found it. Halving is for TaskKit's hundred lines, and
the thousands after that: every look halves the lines left, so a
hundred lines take about seven looks, and you never have to read all
of them closely. Halve the lines in the order they run, which is not
always the order they sit in the file: a function's lines run when it
is called (lesson 5.1), not where it is written. In TaskKit, the lines
of readCommand sit near the top of index.ts, but they run only
when const command = readCommand();, further down, calls it. So in
the run, they come at that line.
Logs that show everything
A log is only as good as what it shows you. Three habits make each
look count.
Give every log a label.console.log("kept:", kept) prints the
name before the value. With three logs in a run, unlabelled output is
three lines you have to match to the code by guessing.
Print a list as a list. It is tempting to put the box in a
template string, the way the program's own output does. Run both
lines:
Bad — the template string turns the
list into one line of text, and the blank title into two commas.
The first prints kept: pay rent,x call mom,,x buy milk, and the
empty title is the gap between two commas, easy to read past. The
second prints kept: [ 'pay rent', 'x call mom', '', 'x buy milk' ],
where '' cannot be missed. The quotes also show spaces at the start
or end of an item, which is where many text bugs hide.
Put square brackets, [ and ], round one text value. A single
text value prints without quotes, so console.log("title:", title)
shows nothing at all for an empty string. Put it in square brackets
inside a template string:
console.log(`title: [${title}]`) prints title: [] for an
empty string and title: [ pay rent] for a space too many.
When the bug is fixed, delete every log you added. They are for you,
not for the people who use the program: left in TaskKit, they would
print between its real lines.
A breakpoint for one turn
A log prints the boxes you named, on every turn of a loop. When the
question is what every box holds on one turn, you want lesson 5.10's
debugger. But a plain breakpoint in a loop stops on every turn, and
the turn you care about may be the fortieth.
A conditional breakpoint stops only when a condition you write is
true, such as tidyTask === "". Node runs every turn at full speed
until that one. Here are the two side by side, on TaskKit's add
loop with a blank title in the middle. The log card shows what
console.log(`tidyTask: [${tidyTask}]`); prints, put for a
moment under const tidyTask = typed.trim();; you do not need to
add it. The breakpoint is on the if below it:
tidyTask: [pay rent]
Added: Pay rent
tidyTask: []
Skipped an empty task
tidyTask: [call mom]
Added: Call mom
A log in the loop
Does: Prints the boxes you named, on every turn, in one run
Never: Shows nothing you did not think to print
VARIABLES
Block newTask: '' tidyTask: '' …Block typed: ' '
A breakpoint, if tidyTask === ""
Does: Shows every box, on the one turn you asked for
Never: Shows none of the turns before it
A log answers for every turn; a breakpoint shows every box
on one
Set that breakpoint in your own TaskKit. You change no code: the
condition lives in VS Code (Visual Studio Code, your editor), not in
the file.
1
Add a conditional breakpoint
Open index.ts in ~/projects/taskkit. In the add case, find the
line if (tidyTask === "") { inside the loop. Right-click in the
gutter, left of its line number, and pick Add Conditional
Breakpoint... from the menu. A text field opens under the line,
with Expression picked on its left. Type the condition the way
you would write it in an if, with ===, and press Enter (Return on
a Mac):
text
tidyTask === ""
A red dot with a small = in it appears in the gutter: that mark
tells a conditional breakpoint from a plain one.
2
Run TaskKit in a JavaScript Debug Terminal
As in lesson 5.10, open the Command Palette:
⌘ Cmd+⇧ Shift+P
Ctrl+Shift+P
Ctrl+Shift+P
Type debug terminal and choose Debug: JavaScript Debug
Terminal. Then add three titles, the middle one a single space:
bash
node index.ts add "pay rent" " " "call mom"
Outputtext
Debugger attached.============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rent
The first turn ran at full speed and added Pay rent. On the second
turn the condition is true, so Node pauses on the if, before that
line runs.
3
Read the boxes, then go on
VARIABLES groups the boxes by the pair of braces { } each box was
made in, and calls each group a Block. The first is the loop's
body: tidyTask: ''. Click the next Block to open it: it holds
the loop's own box, typed, the title it came from: ' '. Below it
are one more Block, for the try, and Module and
Global; leave them closed.
Press Continue: the third turn does not match, so Node runs to
the end and prints the rest:
Outputtext
Skipped an empty taskAdded: Call momTasks added: 2 of 5, room for 3 moreList 40% fullYour list, A to Z:#2 [todo] Call mom, due: not set#1 [todo] Pay rent, due: not setWaiting for the debugger to disconnect...
Click the red dot to remove the breakpoint.
Make it small, keep it fixed
Halving gives you a line. Before you change it, make the problem as
small as it can be: the one line, with the smallest input that still
goes wrong. In TaskKit that saves you retyping a command full of
titles after every change; you run a line or two instead, and try a
fix in seconds. For today.ts, it is line 3 alone, given one task
and one blank:
It prints kept: [ 'pay rent', '' ]: two items in, two out, and the
empty one should be gone. With nothing else around it, the bug has
nowhere to hide.
Once it is fixed, keep that small input. Write it into a test, as in
lesson 5.11: the test runs every time you run node --test, so if
anyone, you included, brings the bug back, you hear about it at once.
TaskKit keeps the fix in a test
Now TaskKit's step for this lesson: today.ts moves into TaskKit as
a function, and the small input becomes its test.
1
Make today.ts
In ~/projects/taskkit, open today.ts, the file from lesson 4.5
(make it if you do not have it), and replace everything in it with an
exported function countLeft. Its body is lines 2 to 4 of the fixed
today.ts, working on the list it is handed, and it gives back how
many tasks are left:
today.tsts
export function countLeft(typed: string[]): number { const titles = typed.map((line) => line.trim()); const kept = titles.filter((title) => title !== ""); const left = kept.filter((title) => !title.startsWith("x ")); return left.length;}
2
Write today.test.ts
One test, as in lesson 5.11, with the small input as your friend
typed it: a task and a blank line of two spaces, since countLeft
trims first.
today.test.tsts
import { test } from "node:test";import assert from "node:assert/strict";import { countLeft } from "./today.ts";test("a blank line is not a task left", () => { assert.equal(countLeft(["pay rent", " "]), 1);});
3
Check and run the tests
Check the files with tsc (short for TypeScript compiler), which
npx starts, then run the tests:
✔ 1 of 4 is 25% (0.400375ms)✔ 2 of 3 is 67% (0.072875ms)✔ capitalize gives buy milk a capital B (0.416791ms)✔ capitalize keeps the rest as typed (0.062708ms)✔ capitalize leaves an empty task empty (0.057ms)✔ 3 tasks of 5 is 60% full (0.058583ms)✔ alphabetical puts buy milk first (7.562375ms)✔ a blank line is not a task left (0.420291ms)ℹ tests 8ℹ suites 0ℹ pass 8ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 86.383583
Eight tests: the seven from Module 5, and this one. The number after
each is how long it took, in ms (milliseconds, thousandths of a
second). The times in brackets differ on every run.
Predict what the log prints
plan.ts adds up the minutes of three tasks and says how many hours
that is. It prints About 13 h (h for hours), which cannot be right
for three short tasks. A log sits in the middle. Work out what it
prints, and from that, which line holds the bug, before you run it.
Predict
Which line holds the bug?
plan.tsts
const minutes = [25, 40, 15];const total = minutes.reduce((sum, minute) => sum + minute, 0);console.log("total:", total);const hours = total / 6;console.log(`About ${Math.round(hours)} h`);
The common mistake: fixing where it shows
Lesson 5.8 said to fix a crash at the source, not on the line where
Node stopped. A quiet bug tempts you in a different way: the wrong
number is right there on the last line, and one small number there
makes it come out right.
Common mistake
Changing the line that prints the wrong number
The count is one too many, so you take one off where it is printed:
Left: 1. The - 1 was never about the count; it hid one blank
line, and now it takes away a real task.
Left: 3
The fix
Fix the first wrong box, on the line that makes it, and take the
- 1 back out. With the blank line it prints Left: 2, as you saw
under "Halve the search"; without it, too:
A fix that adds or takes away a number at the end, to make one
answer come out right, is a patch on where the bug shows. If you
cannot say which line first went wrong, you have not found the bug
yet: halve once more.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Exercise · Read the code
Stop on the blank turn
You want this loop to pause only on the turn where the person typed
a blank title. Which condition do you give the breakpoint on line 4?
ts
const typed = ["call mom", " ", "pay rent"];for (const title of typed) { const tidy = title.trim(); console.log(`Task: ${tidy}`);}
Exercise · Fix the error
Find the first wrong box
shortest should give back the shortest title, tidied: tea for the
first call, go for the second. It gives back the longest. Log the
box each line makes, find the first wrong one, and fix that line.
Delete your logs before you press Check: it compares everything
the code prints.
Loading the editor…
Exercise · Fix the error
Make it small
Halving pointed at line 2. Titles of up to 8 characters count as
short, so pay rent, exactly 8, should be kept. Make the problem
small: cut titles down to the one title that shows the bug, then
fix line 2, so that the program prints short: [ 'pay rent' ].
Loading the editor…
Exercise · Read the code
Where the bug can be
names should be the done tasks without their x : pay rent and
buy milk. Run it and read the two logs. Which lines can the bug
be on?
A log in the middle prints a wrong box. Where is the bug?
Check yourself
Left: 3 should be Left: 2. Where do you fix it?
Check yourself
When does a conditional breakpoint beat a log?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Debugging strategies
What things are
Word
What it means
Quiet bug
Runs to the end, no error, wrong answer
Halving
Look in the middle; keep the half with the bug
Log
A console.log you add only to look
Label
The name before the value: "kept:", kept
Conditional breakpoint
Pauses only when its condition is true
Exception
A thrown value
Code and clicks
Write or do
To
`[${title}]`
Show spaces and the empty string
Right-click the gutter
Choose Add Conditional Breakpoint...
tidyTask === ""
A condition: pause on the blank turn
Turn on Caught Exceptions
Pause where a caught error is thrown
Rules
Rule
What it means
Make it happen
Input, expected and got, written down first
A right box
The bug is below it
A wrong box
The bug is on its line, or above
Lists as lists
Not in a template string: '' vanishes there
Fix where it starts
Never with a number where it shows
Small, then kept
Smallest input that fails; keep it as a test
Logs out
Delete every log once it is fixed
Module 8 on one page
Cheat sheet
Module 8: Errors and Debugging
8.1 A catalogue of common TypeScript errors and how to fix them
Code or rule
What it means
TS and a number
TS for TypeScript, then the number of the message
TS2322
Not assignable: is the value wrong, or the type?
TS2339
Does not exist: spelled as in the type? Narrowed?
The deepest line
The reason, and where the fix goes
Never widen to hide
A wider type lets the mistake through
8.2 Type errors vs runtime errors: why types vanish when the code
runs
Word
What it means
Type error
TypeScript's, found by reading the code
Runtime error
Node's, found at the line while it runs
Types vanish
Nothing stops a wrong value once the code runs
Values from outside
Check them with if before you use them
8.3 throw and try / catch
Write
To
throw new Error("…")
Refuse a value, and say why
try { … }
Try these lines
catch (error) { … }
What to do instead, if one throws
error instanceof Error
Check that it is an error
8.4 Where to throw and where to catch: friendly errors for bad
commands
Write or rule
What it means
throw new Error("… Try: …")
Refuse, and say what to type
Refuse where you check
The line that finds it throws
Catch where you talk
Where the program prints to the person
No made-up answer
A catch that must invent one is too low
A wide catch
Also catches bugs, and hides their line
8.5 any vs unknown: the escape hatch and the safe box
Write or rule
What it means
any
Any value; every use of it passes unchecked
value: unknown
Take any value, and check it before use
typeof value === "string"
Use it as text inside the if
A red line
Fix the code; never hide it with any
8.6 Debugging strategies: console, breakpoints, isolating the
problem
Rule
What it means
Make it happen
Input, expected and got, written down first
A right box
The bug is below it
A wrong box
The bug is on its line, or above
Conditional breakpoint
Pauses only when its condition is true
Fix where it starts
Never with a number where it shows
Where to go next
You can now pin a quiet bug down, halve the lines it can be on with
logs that show everything, stop on the one turn that matters with a
conditional breakpoint, and fix the bug where it starts. Module 8 is
done: you read TypeScript's errors, you know which ones only a run
shows, you throw and catch your own, and you find the ones nobody
reports.
Next is import and export: "type": "module", .ts
extensions, import type, the first lesson of Module 9. TaskKit's
index.ts is now about a hundred lines long; Module 9 splits it into
files, each with one job, so the next bug has fewer lines to hide
in.
Before you move on, see the test do its job. Put the " " back on
line 3 of today.ts in taskkit and run node --test: the test
fails with actual: 2 and expected: 1. Change it back to "",
and run it once more, so TaskKit leaves this module with every test
passing.