Loading

T0 Learning to learn · Lesson 3

The debugging method, and cutting a bug down

Six steps for any bug, with or without a message: reproduce, describe, guess, test, fix, check; labelled prints and trace tables; halving and the smallest example; checking what you are sure of; and checking a fix with ===.

  • follow the six-step method for any bug
  • print values with labels in the right places, and trace a program by hand
  • cut a long program down to the lines that show the bug, by halving
  • test the things you are sure of, and use the rubber duck
  • switch a line off with a comment, and check a fix with ===
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-10-26)Play this lesson's games

The back cover

A bug is a slip that makes a program do the wrong thing. Some bugs come with an error message. Many do not: the program runs to its end and gives a wrong answer, with no report at all. Finding such a slip is called debugging, and it is a skill of its own.

Changing lines at random makes things worse. These pages set out a calm method of six steps that works on any bug, the way a good doctor works on any illness. Around it stand the tools of the trade: prints with labels, a table for following values by hand, a way to cut a program in half again and again, and the habit of testing what seems certain.

The last step matters as much as the first. A fix is finished only when it has been checked, and checked on more cases than the one that showed the bug.

Before you start

The story: The wrong total on Chandler Street

Every lamp on Chandler Street shows the night's oil total, and every one shows the same wrong number. The lamplighters' foreman has checked the tanks by hand three times. "The lamps say 340 litres," he says. "The tanks say 310."

There is no red line this time. No error. The script runs, and it is wrong.

Corin starts changing lines at random, hoping one of them is the fault. Ilse takes the pen out of his hand. "Guessing is not a method," she says. She turns to you. "Find me the one line that is wrong. Prove it before you change anything."

Lessons 1 and 2 taught you to read what the computer says when something goes wrong. But many bugs say nothing at all: the program runs, and the answer is wrong. This lesson gives you a method that finds a bug whether or not there is a message. It builds on these ideas; each has a tiny example.

What you already knowA tiny exampleWhere it comes back
console.log prints a value, and several values with commas.console.log("Total:", 95) prints Total: 95.Printing values is the main tool of this lesson.
Lines run from the top down.A print on line 5 shows the values as they are after lines 1 to 4.A print placed in the middle shows a program halfway through.
let can change.total = total + 40; makes total 40 bigger.Following how a value changes, line by line, finds many bugs.
+ joins when either side is text."4" + 455 is the text 4455.It is behind many wrong answers with no error at all.
typeof tells the type.typeof "4" is string.Checking what you assume about a value.
An error report names a line.at line 3; bill.js:4:26.The line is where to start looking, not always where the slip is.
NaN arrives quietly."abc" * 2 is NaN, with no error.A quiet wrong value needs the method more than a loud error does.
Percent means per hundred.18% of 500 is 500 × 18 ÷ 100, which is 90.Several examples are bills with GST or discounts.
Halving finds things fast.Guessing a number from 1 to 100 with "higher or lower" takes at most 7 guesses if you always guess the middle.Cutting a program in half, again and again, finds the line with the bug.
Explaining a thing aloud shows what you have missed.Telling a friend the route to your house, you notice the turn you forgot.The rubber duck: explaining code line by line.

By the end of this lesson you will be able to:

  • follow a six-step method for any bug: reproduce, describe, guess, test, fix, check;
  • print values with labels in the right places, and follow a value by hand with a trace table;
  • cut a long program down to the few lines that still show the bug, by halving;
  • check the things you are sure of, because that is where bugs hide;
  • switch a line off with a comment, and test a fix with ===, which says true or false.

In one line

This lesson turns printing, the top-down order and the habit of halving into a method that finds bugs with or without an error message.

The method: six steps for any bug

At a glance

Debugging is the work of finding a bug and removing it. A good doctor does not hand out a medicine at the first look, and a good programmer does not change code at the first look either. The method has six steps, always in the same order.

Reproduce the bug: make it happen again, on purpose. Describe it: say what was expected and what came out. Guess one cause. Test that guess with one print. Fix one thing, and only one. Then check that the fix works, with other values as well as the first. The steps are small, and each one leaves something written down, so the search never goes round in circles.

Take a guess: Why is it risky to change three lines at once when hunting for one bug?

When you have a fever, a good doctor does not guess a medicine at once. The doctor asks what is wrong and since when, and takes your temperature. Then the doctor forms a guess ("this looks like a virus") and orders one test to check it. Only then comes the treatment, and a visit later to make sure it worked. Each step uses what the last one found.

Finding a bug works the same way. The steps below look slow on paper. In practice they are the fastest way there is, because each step throws away most of the places the bug could be.

Bug

A slip in a program that makes it do something other than what was meant. Debugging is finding and fixing it.

StepWhat you doThe question it answers
1. Reproducemake the bug happen again, on purpose, the same way every timeCan I see it whenever I want?
2. Describewrite one sentence: what you expected, and what happened instead, with the actual valuesWhat exactly is wrong?
3. Guessname one possible cause, and only oneWhat could make that happen?
4. Test the guessfind the smallest check that would prove the guess right or wrong: usually one printWas I right?
5. Fix one thingchange only what the test showedDoes this change remove the cause?
6. Checkrun again; try other values too; make sure nothing else brokeIs it really fixed?

If the test in step 4 proves the guess wrong, that is not a failure. You have ruled out one cause, and you go back to step 3 with one fewer place to look. Most bugs fall after two or three rounds.

A common mistake

Skipping straight from "it is wrong" to step 5, changing things until the answer looks right. A change that makes the answer look right without a reason often hides the bug instead of fixing it, and it comes back later in a worse place.

The method on a real bug

Worked example 1

A family books 4 train tickets at 455 rupees each, plus a booking fee of 30 rupees. The program prints 445530. Find and fix the bug with the method.

What we have: the program below, and the right total from lesson 1: 4 × 455 + 30 = 1850

What we need: the cause, and a fix that prints 1850

The plan: follow the six steps in order

const qty = "4";
const fare = 455;
console.log(qty + fare * 1 + 30);
445530
  1. 1. Reproduce. Press Run: it prints 445530 every time.
  2. 2. Describe. Expected 1850, got 445530: a number far too big, made of the digits 4, 455 and 30 side by side.
  3. 3. Guess. The digits sitting side by side look like text being joined. Guess: qty is a string, so + joins.
  4. 4. Test. Print qty with its type:
const qty = "4";
console.log(qty, typeof qty);
4 string
  1. The guess was right: qty is the text 4. Also, qty + fare * 1 adds where it should multiply. That is a second slip, found while looking at the first.
  2. 5. Fix. Make qty a number and multiply it by the fare:
const qty = 4;
const fare = 455;
console.log(qty * fare + 30);
1850
  1. 6. Check. 4 × 455 = 1820, and 1820 + 30 = 1850. Try 1 ticket in your head: 455 + 30 = 485; change qty to 1 and Run: it prints 485.

qty was text and the formula added instead of multiplying; with const qty = 4; and qty * fare + 30 it prints 1850.

Check: the six steps found both slips, and the check with a second value agrees with a sum done by hand.

A path that fails: changing + 30 to - 30 because the answer "looked too big". It now prints 4425: the minus turns the joined text 4455 into a number and takes 30 away. Still nonsense, and now the fee is subtracted too.

Worked example 2

A shop adds 18% GST to a price of 500 rupees and prints 518. Use the method.

What we have: a price of 500, a GST rate of 18%, and the right answer 500 + 18% of 500 = 590

What we need: the cause and the fix

The plan: describe with the actual numbers; the difference between expected and actual is a strong clue

const price = 500;
const gst = 18;
console.log(price + gst);
518
  1. Describe. Expected 590, got 518. The difference is 72; and 518 is exactly 500 + 18.
  2. Guess. The program adds the rate itself, 18 rupees, instead of 18% of the price.
  3. Test. 18% of 500 is 500 × 18 ÷ 100 = 90, and 500 + 90 = 590. The code never works out a percentage, so the guess holds.
  4. Fix.
const price = 500;
const gst = 18;
console.log(price + price * gst / 100);
590
  1. Check. Try a price of 100: 100 + 18 = 118, which matches 18% GST by hand.

The program added 18 rupees, not 18%; price + price * gst / 100 prints 590.

Check: for any price, the GST part should be 18% of it, and 590 − 500 = 90 = 18% of 500.

When you are stuck: you do not know where to start

Do step 2 on paper: "I expected ___ and got ___." Put the real values in the blanks.

Look at how the wrong value differs from the right one: too big, too small, digits side by side, NaN. Each pattern suggests a cause.

Make one guess, and test it with one print. Never two guesses at once.

Your turn

Put the six steps in order: fix, guess, check, reproduce, test, describe.Tap to reveal
  1. First you need to see the bug, then say what it is, then think about why, then prove it, then change it, then confirm.

Reproduce, describe, guess, test, fix, check.

A total comes out as 5000 instead of 500. What does the size of the mistake suggest?Tap to reveal
  1. 5000 is exactly 10 times 500.
  2. Something was multiplied by 10 too many, or a 0 was joined on as text.

A factor of 10: look for an extra × 10 or a joined digit.

Your guess was wrong: the print showed the value you expected. Was the test wasted?Tap to reveal
  1. The test ruled out one cause.

No: one place is ruled out; go back to step 3 with a new guess.

Did you know?

A method in four lines, from 1945

In 1945 the mathematician George Pólya published a small book called How to Solve It. It begins with a short checklist of four phases for solving a problem in mathematics. Understand the problem. Make a plan. Carry out the plan. Look back. He added that the phases are not rigid: a solver may move back and forth between them. The book has sold over a million copies and has been translated into more than 15 languages.

Why it fits here: The six steps of debugging follow the same path: understand the bug, plan one test, carry it out, and look back to check the fix.

Sources: Wikipedia: How to Solve It; MacTutor, University of St Andrews: George Pólya

Bugs are older than computers

The word bug for a fault was not born with computers. Engineers were using it in the 1870s. In 1878 the inventor Thomas Edison wrote to an associate about his work. First comes the idea, he said. Then the difficulties arise, and bugs, as such little faults and difficulties are called, show themselves. So when a dead moth was found in a relay of a Harvard computer in 1947, the word was already waiting for it.

Why it fits here: Step one of the method is to find the bug before fixing anything, and the word itself comes from engineers who hunted faults the same way.

Sources: IEEE Spectrum: Did You Know? Edison Coined the Term Bug; Wikipedia: Software bug

In one line

Reproduce, describe (expected and actual), guess one cause, test it with one print, fix one thing, and check with other values too.

Printing to see, and tracing by hand

At a glance

A running program is like a closed box: values go in, an answer comes out, and the steps between cannot be seen. A print is a small window cut into the box. One print placed before a suspect line and another placed after it show the value going in and the value coming out. Each print carries a label, a few words that say which value it is, so that the output can be read without guessing.

A trace table does the same work on paper. It has a column for each name and a row for each line, filled in by hand as if you were the computer. Either way, the slip sits between the last value that was right and the first value that was wrong.

Take a guess: A label is only a few extra words: what goes wrong when five prints have no labels?

A program is a box you cannot see into. You see what goes in and what comes out, and when the output is wrong, you have no idea which step inside went wrong. A print is a small window cut into the side of the box. Put a few windows in the right places and you can watch the value change, step by step, until you see the moment it goes wrong.

Label every print

A print with no label leaves you guessing which line printed which number. Always put a short label first, saying what the value is and where you are.

const price = 1000;
let total = price;
total = total - total * 10 / 100;
console.log("after the first discount:", total);
total = total - total * 10 / 100;
console.log("after the second discount:", total);
after the first discount: 900
after the second discount: 810

Read the output like a diary of the program. After the first discount the total is 900. After the second it is 810. If the shop meant to give only one 10% discount, the diary shows exactly where the second one crept in.

Where to put prints

Put one just before the line you suspect, showing the values it uses, and one just after, showing what it made. If the values before are right and the value after is wrong, the slip is on that line. If the values before are already wrong, move up.

A trace table: printing in your head

Sometimes you have no computer at hand, or you want to understand a program before running it. Then you trace it by hand. A trace table has one row for each line that runs and one column for each name. You fill in each value as the line changes it, exactly as the computer would.

let stock = 50;
stock = stock - 12;
stock = stock + 30;
stock = stock - 25;
console.log(stock);
43
LineWhat it doesstock
1make stock, put 50 in it50
250 − 1238
338 + 3068
468 − 2543
5print stock43 (printed)

The table agrees with the output, so the program does what we think. When a trace table and a real run disagree, the line where they first differ is where your understanding, or the code, is wrong. Both are worth knowing.

Worked example 3

A kirana shop's evening stock of rice should be 38 kg: it opened with 50 kg, sold 12 kg, received 25 kg and sold 25 kg. The program prints 88. Find the slip with labelled prints.

What we have: the program and the right answer: 50 − 12 + 25 − 25 = 38

What we need: the line that goes wrong

The plan: print the stock after every line, with a label, and compare with the sum by hand

let rice = 50;
rice = rice - 12;
rice = rice + 25;
rice = rice + 25;
console.log("evening:", rice);
evening: 88
  1. Add a labelled print after each change:
let rice = 50;
rice = rice - 12;
console.log("after the first sale:", rice);
rice = rice + 25;
console.log("after the delivery:", rice);
rice = rice + 25;
console.log("after the second sale:", rice);
after the first sale: 38
after the delivery: 63
after the second sale: 88
  1. By hand: 38 after the sale, 63 after the delivery, then 63 − 25 = 38 after the second sale. The first two prints agree with the hand sum. The third does not: it went up instead of down.
  2. So the slip is the line after the delivery: it adds where it should subtract.

The second sale was written as + 25; with rice = rice - 25; the program prints evening: 38.

Check: the first wrong print sits right after the faulty line, which is the rule: the slip is between the last right value and the first wrong one.

Worked example 4

Trace this program by hand, then run it to check your table.

What we have: a program that changes two names

What we need: the values of both names after every line, and the output

The plan: one row per line, one column per name; work out the right side first, then store it

let runs = 0;
let balls = 0;
runs = runs + 4;
balls = balls + 1;
runs = runs + 6;
balls = balls + 1;
console.log(runs, balls);
10 2
  1. Line 1: runs 0. Line 2: balls 0. Line 3: runs 4. Line 4: balls 1. Line 5: runs 10. Line 6: balls 2. Line 7 prints both.

The table ends with runs 10 and balls 2, and the program prints 10 2.

Check: the run and the table agree at the end, so every row was right.

Worked example 5

A results portal adds 5 bonus marks to 412.5 out of 500 and prints the percentage as 82.51. By hand it should be (412.5 + 5) ÷ 500 × 100 = 83.5. Find the slip.

What we have: the program, its output 82.51, and the right answer 83.5

What we need: the value that is not what it seems

The plan: the answer is almost right, so the formula is nearly right; print the values it uses, with their types

const marks = "412.5";
const bonus = 5;
const maximum = 500;
console.log("percent:", (marks + bonus) / maximum * 100);
percent: 82.51
  1. Print the values inside the brackets, with labels and types:
const marks = "412.5";
const bonus = 5;
console.log("marks:", marks, typeof marks);
console.log("with bonus:", marks + bonus);
marks: 412.5 string
with bonus: 412.55
  1. marks is text, so + joined the 5 on as a digit: 412.55, not 417.5. Then / turned 412.55 into a number, so the answer looked almost right.
const marks = Number("412.5");
const bonus = 5;
const maximum = 500;
console.log("percent:", (marks + bonus) / maximum * 100);
percent: 83.5

marks was text; with Number("412.5") the portal prints percent: 83.5.

Check: 417.5 ÷ 500 = 0.835, and 0.835 × 100 = 83.5, the answer worked by hand.

A path that fails: looking only at the formula. It was right; the plain output 412.5 looks the same for text and for a number, so only the print with typeof showed the real slip.

When you are stuck: too many prints to read

Give each print a short, different label, so you can tell them apart at a glance.

Print only the values the suspect line uses, not everything.

When the bug is found, delete the prints, or turn them off with a comment (the next section).

Your turn

let fare = 200;
fare = fare + 50;
console.log("after the fee:", fare);
fare = fare * 2;
console.log("return ticket:", fare);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
after the fee: 250
return ticket: 500
  1. fare becomes 200 + 50 = 250, and the first print shows it.
  2. Then fare becomes 250 × 2 = 500.

after the fee: 250, then return ticket: 500.

The value before a line is right and the value after it is wrong. Where is the slip?Tap to reveal
  1. The line in between is the only thing that changed the value.

On that line.

Make a trace table for let x = 3; x = x * x; x = x - 1;.Tap to reveal
  1. Line 1: 3.
  2. Line 2: 3 × 3 = 9.
  3. Line 3: 9 − 1 = 8.

x is 3, then 9, then 8.

Did you know?

Careful thought, and a few prints

Brian Kernighan is a computer scientist who worked at Bell Labs, and he is a co-author of the first book on the C language. In 1979 he wrote a guide for newcomers called UNIX for Beginners. The system had a special tool for examining failed programs, which he found rather hard to learn. Then he added a line that programmers still repeat. The most effective debugging tool is still careful thought, coupled with judiciously placed print statements. Judiciously means with good judgement.

Why it fits here: A labelled print before the suspect line and one after it are what he meant: few prints, each placed with thought.

Sources: UNIX Programmer's Manual, Seventh Edition, Volume 2A: UNIX for Beginners; Wikiquote: Brian Kernighan

The day a pioneer saw his future

Maurice Wilkes led the team that built EDSAC at the University of Cambridge, one of the first computers to keep its program in its own memory. It ran from May 1949. Wilkes later described a moment from that time. Walking between the computer room and the punching machines, he paused on the stairs. It came over him with full force, he wrote, that a good part of the rest of his life would be spent in finding errors in his own programs.

Why it fits here: Even the builders of the first computers had to hunt for their own slips, one value at a time, as a trace table does.

Sources: Wikiquote: Maurice Wilkes; Wikipedia: Maurice Wilkes; Wikipedia: EDSAC

In one line

Put labelled prints before and after the suspect line, or trace by hand with a table; the slip sits between the last right value and the first wrong one.

Cutting a bug down

At a glance

A comment is a note in the code that the computer skips. In JavaScript it starts with two slashes. Two slashes put in front of a line switch that line off without deleting it, which is called commenting out.

With that switch, a long program can be searched fast. A print in the middle shows whether the value is still right there. If it is, the slip lies in the second half; if not, in the first. Halving again and again rules out half of what is left each time, so even 64 lines need only six rounds. A crash can be cut down as well: lines are taken out until the smallest example that still shows the bug remains. In so small a program the slip has nowhere to hide.

Take a guess: A program has 64 lines and one slip: how many halvings are needed to corner it?

When the lights of a whole house go out, an electrician does not test every bulb. She goes to the switchboard and turns off half the switches. If the fuse holds, the fault is in that half; if it trips again, it is in the other half. Then she halves again. Even in a house with 64 switches, six rounds of halving find the faulty one, because 64 halves to 32, 16, 8, 4, 2 and 1.

A long program can be searched the same way. This section gives you two tools for it: switching a line off, and halving.

New idea: a comment switches a line off

Two slashes, //, start a comment: everything after them on that line is a note for people, and the computer skips it. Lesson 1's quick card used comments to explain its lines. A comment can also switch a line of code off, without deleting it. This is called commenting out a line.

console.log("one");
// console.log("two");
console.log("three");
one
three

The second line did not run. To switch it back on, delete the two slashes. Commenting out is safer than deleting, because the line is still there, exactly as it was, when you want it back.

Halving with prints

Here is an electricity bill program of 11 lines. The bill should be 3040.94 rupees: 340 units at 7.50 rupees, plus 16% duty, plus a fixed charge of 120 and meter rent of 25, less a 2% rebate for paying on time. It prints something else.

const units = 340;
const ratePerUnit = 7.5;
const fixedCharge = 120;
const energy = units * ratePerUnit;
const duty = energy * 16 / 100;
const meterRent = 25;
const subtotal = energy + duty + fixedCharge;
let total = subtotal + meterRent;
const rebate = total * 2 / 100;
total = total + rebate;
console.log("Total:", total.toFixed(2));
Total: 3165.06

Instead of checking all 11 lines, check the middle first. Put one labelled print after line 5 and work out the right values by hand: 340 × 7.5 = 2550, and 16% of 2550 = 408.

const units = 340;
const ratePerUnit = 7.5;
const fixedCharge = 120;
const energy = units * ratePerUnit;
const duty = energy * 16 / 100;
console.log("energy and duty:", energy, duty);
const meterRent = 25;
const subtotal = energy + duty + fixedCharge;
let total = subtotal + meterRent;
const rebate = total * 2 / 100;
total = total + rebate;
console.log("Total:", total.toFixed(2));
energy and duty: 2550 408
Total: 3165.06

Both are right, so lines 1 to 5 are fine: the slip is in lines 6 to 11. Halve again: print the total after line 8. By hand: 2550 + 408 + 120 = 3078, and 3078 + 25 = 3103.

const units = 340;
const ratePerUnit = 7.5;
const fixedCharge = 120;
const energy = units * ratePerUnit;
const duty = energy * 16 / 100;
const meterRent = 25;
const subtotal = energy + duty + fixedCharge;
let total = subtotal + meterRent;
console.log("before the rebate:", total);
const rebate = total * 2 / 100;
total = total + rebate;
console.log("Total:", total.toFixed(2));
before the rebate: 3103
Total: 3165.06

Right again. Only lines 9 to 11 are left. The rebate is 2% of 3103, which is 62.06, and a rebate is taken off the bill. Line 10 adds it. That is the slip: three prints, and 11 lines became 1.

const units = 340;
const ratePerUnit = 7.5;
const fixedCharge = 120;
const energy = units * ratePerUnit;
const duty = energy * 16 / 100;
const meterRent = 25;
const subtotal = energy + duty + fixedCharge;
let total = subtotal + meterRent;
const rebate = total * 2 / 100;
total = total - rebate;
console.log("Total:", total.toFixed(2));
Total: 3040.94

Why halving is fast

Each print rules out half of the lines that are left. 11 lines need about 4 prints; 1000 lines need about 10. Checking one line at a time would need up to 1000.

The smallest example that still shows the bug

When a long program crashes, copy it somewhere safe, then cut it down. Comment out or delete anything that the error does not need, run after every cut, and keep only the lines without which the error disappears. What is left is the smallest example, often 2 or 3 lines. On Stack Overflow it is called a minimal reproducible example, and it is what helpers ask for first.

Worked example 6

A receipt program crashes. Cut it down to the smallest example that still shows the error.

What we have: a 7-line program and its error

What we need: the fewest lines that still give the same error

The plan: comment out one line at a time, from the end; keep a line only if the error goes away without it

const shop = "Asha Stores";
let customer;
const items = 3;
const total = items * 40;
console.log(shop.toUpperCase());
console.log("Customer:", customer.toUpperCase());
console.log("Total:", total);
ASHA STORES
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at line 6
  1. Line 7 never runs, so it cannot matter: cut it. Lines 3, 4 and 5 make and print other values; comment them out, run: the same error. They are not needed.
  2. Line 1 is used only by line 5, which is gone: cut it too. Run again: the same error, now at the new line 2.
let customer;
console.log("Customer:", customer.toUpperCase());
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at line 2
  1. Could line 1 go as well? Comment it out: the error changes to a ReferenceError, because customer would not exist. So line 1 is part of the bug: keep it.

The smallest example is two lines: a let with no value, and a method called on it.

Check: with these two lines, the bug is plain to see: customer is never given a value. In the full program the same slip was hidden among unrelated lines.

A path that fails: cutting a line and not running before the next cut. If the error changes after two cuts, you cannot tell which cut changed it; one cut, one run.

When you are stuck: a bug in a long program

Halve: put one labelled print in the middle, and work out by hand what it should show.

If it is right, the slip is below; if it is wrong, above. Halve the half.

For a crash, copy the program and cut it down, one line at a time, running after each cut.

Switch lines off with // rather than deleting them, so that nothing is lost.

Your turn

// const price = 40;
const price = 45;
console.log(price);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
45
  1. Line 1 is a comment, so it does not run.
  2. Line 2 makes price 45.

It prints 45; with the comment there is no clash between two consts.

How many halving prints does it take, at most, to find the faulty line among 16 lines?Tap to reveal
  1. 16 halves to 8, 4, 2, 1: four halvings.

4.

Why do helpers ask for the smallest example rather than your whole program?Tap to reveal
  1. In two lines, the slip has nowhere to hide.
  2. Nobody can run your whole project, with its files and settings, on their own laptop.

Because it shows the bug and nothing else, so anyone can run it and see the cause; often you find the slip yourself while making it.

Did you know?

One wolf in Alaska

In November 1982 a one-page piece in the journal Communications of the ACM gave halving a name that stuck: the Wolf Fence algorithm. Its author, Edward Gauss, put it as a puzzle. There is one wolf in Alaska; how do you find it? First build a fence down the middle of the state, and wait for the wolf to howl. Now you know which side it is on. Do the same on that side only, again and again, until you can see the wolf.

Why it fits here: A print in the middle of a program is the fence, and the wrong value is the howl: it tells which half to search next.

Sources: ACM Digital Library: The Wolf Fence algorithm for debugging; Wikipedia: Debugging

A tool that halves for you

Programmers keep the history of their code in a tool called Git, which saves each change as a step that can be visited again. Suppose a program worked last month and is broken today, with a thousand changes in between. Git has a command for this, git bisect. You mark one old step as good and one new step as bad. Git picks a step between the two and asks which it is. About ten answers are enough to reach the one change that brought the bug in.

Why it fits here: It is the halving of this topic, done by a machine: each answer rules out half of the changes that are left.

Source: Git documentation: git-bisect

In one line

A comment, //, switches a line off. Halving with prints rules out half the lines each time, and cutting a crash down to the smallest example leaves the slip with nowhere to hide.

Check what you are sure of

At a glance

An assumption is something taken as true without being checked. Bugs hide there. A value that must surely be a number, a line that must surely have run, a name that must surely be spelled right: none of these gets tested, because each seems certain. So the search goes round the same places again and again.

The way out is to write the assumptions down as a list and to test each one with a single print. Two more habits help. One is to explain the code aloud, line by line, to a rubber duck or to anything that will listen, which is called rubber duck debugging. The other is to take a break, because a rested mind often sees at once what a tired one missed.

Take a guess: Where do lost keys usually turn up: in a place searched three times, or in one you were sure about?

You lose your house keys. You search the kitchen, the bag, the car, three times each. Your mind skips the coat pocket, because you are sure you never put them there. And that is exactly where they are.

Bugs hide in the same place: in what you are sure of. You do not test it, because you know it is right. So the first time a search fails, list the things you have been assuming, and test each one with a print.

Assumption

Something you believe about your program without having checked it: "this is a number", "this line runs", "this name holds the new value".

The assumptionHow to test it in one line
"It is a number."console.log(typeof price, price);
"This line runs."console.log("reached line 12"); just before it
"It holds the new value."print it right after the line that changes it
"These two names are the same."print both; check the capitals letter by letter
"I am running the code I just changed."add console.log("version 2"); at the top and see whether it prints

The last row sounds silly, but it catches experienced developers every week: the file was not saved, or a different copy of the file was run, or the page was not reloaded. A one-line print at the top answers it in a second.

Worked example 7

A developer is sure that the discount line runs. The final price is still 1000. Test the assumption.

What we have: a program where the discount seems to have no effect

What we need: whether the discount line really runs, and if it does, what it does

The plan: print a marker and the value right after the discount line

let price = 1000;
const discount = 10;
price - price * discount / 100;
console.log("final:", price);
final: 1000
  1. Add a labelled print right after line 3:
let price = 1000;
const discount = 10;
price - price * discount / 100;
console.log("after the discount line:", price);
console.log("final:", price);
after the discount line: 1000
final: 1000
  1. The line runs, but price is still 1000. Look at it again: it works out 1000 − 100 and then throws the answer away. Nothing puts the result back into price.
let price = 1000;
const discount = 10;
price = price - price * discount / 100;
console.log("final:", price);
final: 900

The line ran but never stored its result; price = price - price * discount / 100; prints final: 900.

Check: 10% of 1000 is 100, and 1000 − 100 = 900.

A path that fails: assuming "the line runs, so it works". Running and storing are two different things; the print right after the line showed the value had not changed.

The rubber duck

Many developers keep a small rubber duck on their desk. When they are stuck, they explain their code to the duck, out loud, one line at a time: what the line does, and why. It sounds like a joke, but it works so well that it has a name: rubber duck debugging.

Why does it work? When you read your own code silently, your mind fills in what you meant. When you explain each line aloud, you must say what is really there, and the gap between what is there and what you meant becomes audible. A friend, a pet or a notebook works as well as a duck.

Worked example 8

Explain this program to the duck, line by line, and find the slip.

What we have: a program that should print the average of three cricket scores, 45, 60 and 30, which is 45

What we need: the slip, found by explaining each line

The plan: say aloud what each line does, with the real values

const first = 45;
const second = 60;
const third = 30;
const total = first + second + third;
console.log(total / 2);
67.5
  1. "Line 1: first is 45. Line 2: second is 60. Line 3: third is 30."
  2. "Line 4: total is 45 + 60 + 30, which is 135."
  3. "Line 5: print the total divided by... 2. But there are three scores." The slip is heard the moment it is said.
const first = 45;
const second = 60;
const third = 30;
const total = first + second + third;
console.log(total / 3);
45

The program divided by 2 for three scores; dividing by 3 prints 45.

Check: the average 45 lies between the lowest score, 30, and the highest, 60.

Take a break

After 30 minutes on the same bug, a short walk often does more than another 30 minutes at the screen. Your mind keeps working on the problem in the background, and it lets go of the wrong assumption it has been stuck on. Many bugs are solved in the first two minutes after coming back.

When you are stuck: you are sure the code is right and it still does not work

Write down every assumption you are making, even the ones that feel certain. Test each with one print.

Add a print at the very top to make sure the code you are running is the code you changed.

Explain the code aloud, line by line, to a duck, a friend or a notebook.

Take a ten-minute break, then start again from step 2 of the method: describe what you expected and what you got.

Your turn

How do you test the assumption "this line runs"?Tap to reveal
  1. Put a labelled print just before it.

Add a print such as console.log("reached the tax line"); just before it: if it never prints, the line never ran.

let score = 10;
score + 5;
console.log(score);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
10
  1. Line 2 works out 15 but does not store it anywhere.
  2. score is still 10.

It prints 10: the sum was worked out and thrown away.

Why does explaining code aloud help find a slip?Tap to reveal
  1. Reading silently, your mind sees what you meant.
  2. Speaking, you must say what is really written.

Because you have to say what is really there, and the gap between that and what you meant becomes clear.

Did you know?

The testing tool that was wrong

The Hubble Space Telescope was launched in April 1990. Two months later NASA announced that it was flawed: its pictures were blurred. The main mirror had the wrong curve, too flat near its outer edge. Investigators traced the cause to the device that had been used to test the mirror's shape while it was polished. Inside that device, the spacing of one lens was off by 1.3 millimetres. The mirror had been shaped with great care to match a faulty test. Astronauts fitted corrective optics in December 1993.

Why it fits here: The makers were sure of their testing device and did not test it. The fault sat in the one thing nobody doubted.

Source: NASA Science: Hubble's Mirror Flaw

Sleep on it: a measured effect

Taking a break is more than folk wisdom. In January 2004 the journal Nature published a study called Sleep inspires insight. People practised a task that held a hidden rule, a shortcut that nobody told them about. Then some of them slept for eight hours, and the others stayed awake. When all were tested again, more than twice as many of the sleepers had found the hidden rule. The authors concluded that sleep reworks what has just been learned.

Why it fits here: The advice in this topic to take a break when stuck has a measured effect behind it: rest can show what hard staring missed.

Source: Nature: Sleep inspires insight (Wagner and others, 2004)

In one line

Bugs hide in what you are sure of: list your assumptions and test each with one print, explain the code aloud line by line, and take a break when stuck.

Checking the fix

At a glance

A fix is finished only when it has been checked. The sign === asks a question: are these two values exactly equal, in value and in type? The answer is one of two special values, true or false, which are called booleans. So a line can compare what the program gives with an answer worked out by hand, and print true when the two match.

One matching case proves little. A good check uses several cases, each worked out by hand first. It also includes the awkward ones: zero, one, a very large number, an empty string, a decimal. Bugs love such edges. Lines like these, kept and run again after every change, are a first form of what programmers call tests.

Take a guess: Is the text "5" exactly equal to the number 5 in JavaScript?

A mechanic who fixes a car's brakes does not hand back the keys after one look. He drives it round the block, brakes gently, then hard, then on a slope. A fix is finished only when it has been checked, and checked on more than the one case that showed the bug. This is step 6 of the method.

New idea: === asks "is exactly equal to?"

Lesson 1 promised an operator for checking whether two values are equal. It is three equals signs, ===, read aloud as "is exactly equal to". Its answer is not a number or a string but one of two special values: true or false. Values of this kind, with only those two possibilities, are called booleans, after George Boole, who worked out their rules in the 1840s.

console.log(135 === 135, 2 === 3, "135" === 135);
console.log(typeof true);
true false false
boolean

Look at the third check. "135" is text and 135 is a number, so they are not exactly equal, although they look alike. === compares the type as well as the value. That makes it a perfect tool for catching the text-and-number slips of the last two lessons.

A common mistake

Writing one equals sign when you mean a check. price = 40 puts 40 into price; price === 40 asks whether price is 40. JavaScript also has a two-sign ==, which turns text into numbers before comparing; the JavaScript step explains why this school uses === every time.

Checking a fix with true and false

Instead of reading numbers and comparing them in your head, let the program compare them. Write the answer you worked out by hand, and print whether the program's value is exactly equal to it. A column of true means every check passed.

const qty = 4;
const fare = 455;
const total = qty * fare + 30;
console.log("total is 1850:", total === 1850);
total is 1850: true

More than one case, and the awkward ones

A fix that works for the value that showed the bug may still fail for others. Check a few ordinary values, then the awkward ones: zero, one, a very large number, an empty string, a decimal. Bugs love the edges.

Worked example 9

A team scored 287 runs in 49.3 overs. The run rate (runs per over) prints as 5.82, but a cricket scorer says it is 5.80. Find the slip, fix it, and check the fix on several cases.

What we have: 287 runs; 49.3 overs; the scorer's answer 5.80

What we need: the right run rate, and checks that the fix works

The plan: describe, guess, test, fix, then check with values worked out by hand

const runs = 287;
const overs = 49.3;
console.log((runs / overs).toFixed(2));
5.82
  1. Describe. Expected 5.80, got 5.82: close, so the formula is nearly right.
  2. Guess. In cricket, 49.3 overs means 49 overs and 3 balls, and an over has 6 balls. So 49.3 overs is 49 and a half overs, 49.5, not 49.3. The program treats the scorer's notation as a decimal.
  3. Test. 287 ÷ 49.5 = 5.797..., which rounds to 5.80. The guess holds.
  4. Fix. Split the overs into whole overs and balls, and turn the balls into a part of an over:
const runs = 287;
const fullOvers = 49;
const balls = 3;
const overs = fullOvers + balls / 6;
console.log((runs / overs).toFixed(2));
5.80
  1. Check on several cases worked out by hand: 300 runs in 50.0 overs is 6; 60 runs in 9.3 overs is 60 ÷ 9.5; and 0 runs in 10 overs is 0.
console.log("300 in 50:", 300 / (50 + 0 / 6) === 6);
console.log("60 in 9.3:", 60 / (9 + 3 / 6) === 60 / 9.5);
console.log("0 in 10:", 0 / (10 + 0 / 6) === 0);
300 in 50: true
60 in 9.3: true
0 in 10: true

The overs were read as a decimal; with fullOvers + balls / 6 the run rate prints 5.80, and three checks print true.

Check: the fix agrees with the scorer, and with three cases worked out by hand, including zero runs.

A path that fails: taking 0.02 off the answer so that it shows 5.80. The patch fits this one match and no other: for 60 runs in 9.3 overs it gives 6.43 where the right rate is 6.32. Only the real cause, the over notation, fixes every case.

Worked example 10

Check a GST fix on an awkward value: a price of 0.

What we have: the fixed formula price + price * 18 / 100 from the method section

What we need: proof that it works for 0, for 100 and for 500

The plan: print one true or false check per case, each with a label

const gst = 18;
console.log("500:", 500 + 500 * gst / 100 === 590);
console.log("100:", 100 + 100 * gst / 100 === 118);
console.log("0:", 0 + 0 * gst / 100 === 0);
500: true
100: true
0: true

All three checks print true: the formula gives 0 GST on a price of 0, as it should.

Check: the checks were worked out by hand first; the program only confirms them.

Checks that stay

Professional developers keep checks like these in files of their own, called tests, and run all of them after every change. If an old bug comes back, a test turns false at once. The API testing step builds real test files; the code tasks in this school's games already run hidden tests on your answers.

Comparing decimals

Because of the decimal surprise, 0.1 + 0.2 === 0.3 is false. For money, count in paise, as whole numbers; for other decimals, compare after rounding, for example (0.1 + 0.2).toFixed(2) === "0.30", which is true.

When you are stuck: a fix that you are not sure of

Work out three answers by hand first: an ordinary case, the case that showed the bug, and an awkward one (0, 1, a big number, empty text).

Print one labelled === check for each.

If any prints false, the fix is not finished: go back to step 3 of the method.

Your turn

console.log(10 === 10, "10" === 10, 10 === 10.0);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true false true
  1. 10 and 10 are the same number: true.
  2. Text 10 and the number 10 differ in type: false.
  3. 10.0 is the same number as 10: true.

It prints true false true.

What is the difference between total = 95 and total === 95?Tap to reveal
  1. One equals sign puts a value in.
  2. Three ask a question and answer true or false.

total = 95 sets total to 95; total === 95 asks whether total is 95.

A fix works for the price 500. Name two more prices worth checking.Tap to reveal
  1. An ordinary different value, and an awkward one.

For example 100, and the awkward 0.

Did you know?

The mistake no astronaut would make

Margaret Hamilton's team developed the flight software for the Apollo missions. Some evenings she brought her young daughter Lauren to work. One day Lauren, playing astronaut, pressed keys on the simulator and crashed it. She had started a program meant to run only before launch. Hamilton asked to add a safeguard. She was told that astronauts were too well trained to make such a mistake. On the very next mission, Apollo 8, an astronaut did exactly what Lauren had done, and the navigation data was wiped out.

Why it fits here: This is the awkward case of this topic: the one that seems too unlikely to check. A check for it would have cost a few lines.

Sources: The Guardian: interview with Margaret Hamilton, 2019; Wired: Her Code Got Humans on the Moon

Tests show bugs, never their absence

Edsger Dijkstra, a Dutch computer scientist, gave a famous lecture in 1972 called The Humble Programmer. One line of it is still quoted wherever software is tested. Program testing, he said, can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence. A test that fails proves that there is a bug. A test that passes proves only that this one case works.

Why it fits here: That is why a check uses several cases, and why the awkward ones matter most: each new case can only find a bug, never prove that none is left.

Sources: E. W. Dijkstra Archive: The Humble Programmer (EWD340); Wikiquote: Edsger W. Dijkstra

In one line

=== asks whether two values are exactly equal, type included, and answers true or false; check every fix on several cases worked out by hand, awkward ones included.

Where it is used

This method is how debugging is done everywhere, from a student's first program to the systems of banks and airlines. Only the tools get bigger.

What you learnedWhere it is usedA real example
reproduce firstevery bug report in every companya bug ticket must say the exact steps that make the bug happen; one that "happens sometimes" is sent back for steps
describe: expected and actualbug reports, support tickets, questions on Stack Overflow"Expected the cart total 1850, got 445530 after adding 4 tickets" gets fixed in an hour; "the cart is broken" waits for days
labelled printsevery language; servers write them to log filesa delivery app logs "order 5012: payment received" at each step, so that a stuck order shows the last step it reached
trace tablesexams, interviews, reading new codecoding interviews often ask you to trace a short program by hand and say what it prints
halvingsearching big programs and long histories of changesGit, the tool for a project's history (it has its own step), has a command, git bisect, that halves the list of past changes to find the one that brought a bug in
the smallest exampleasking for help, reporting a library's bugthe issue form of most open-source projects on GitHub asks for a minimal reproducible example
checking assumptionsevery debugging session that has gone on too longa fix "does nothing" because the old copy of the file was running; a print at the top shows it
the rubber duckpair programming and code reviewexplaining a change to a colleague, a developer spots the slip before the colleague says a word
checks with ===automated tests (the API testing step)a payments company runs thousands of checks after every change, so that a wrong rounding of paise is caught before it reaches a customer

Mistakes and debugging

These are the habits that make debugging slow. Each has a fix you already know.

1. Changing things at random

Trying one change after another until the output looks right feels quick and is the slowest way of all. Each random change can add a new slip. The fix: make one guess, test it with one print, and change only what the test showed.

2. Patching the output instead of the cause

const total = 445530;
console.log(total - 443680);
1850

This prints the right number for this one case and nonsense for every other. It hides the bug. The fix: keep asking why the value is wrong until you reach the line that made it wrong.

3. Prints with no labels

const a = 40;
const b = 3;
console.log(a);
console.log(b);
console.log(a * b);
40
3
120

With three numbers, you can still tell them apart. With thirty, you cannot. The fix: console.log("price:", a);.

4. Computing something and throwing it away

let price = 1000;
price * 0.9;
console.log(price);
1000

The second line works out 900 and stores it nowhere. The fix: price = price * 0.9;. A line that works out a value but has no = and no console.log is often a slip.

5. Forgetting the prints

Prints left in a finished program fill the console of every user with noise, and sometimes show private data. The fix: remove them, or comment them out, once the bug is fixed.

6. Checking only the case that showed the bug

The fix: check at least three cases worked out by hand, and one of them awkward: zero, one, empty text or a very large number.

The debugging corner: keep a bug diary

For a week, write one line for every bug you fix: what it looked like, and what the cause was. You will see the same few causes again and again: text that should be a number, a value never stored, a missing value, a misspelt name. After a week, you will start checking those first, and most bugs will take minutes.

Quick card

The method and its tools on one card.

StepDoTool
1. Reproducemake it happen on purposeRun, the same input each time
2. Describe"expected ___, got ___"the real values, written down
3. Guessone causethe shape of the wrong value: too big, joined digits, NaN
4. Testthe smallest checkconsole.log("label:", value, typeof value)
5. Fixone changeonly what the test showed
6. Checkseveral cases, awkward ones tooconsole.log("case:", value === expected)

The tools in code

// switch a line off: everything after // is skipped
// console.log("not now");

// a labelled print, with the type
const price = 40;
console.log("price:", price, typeof price);

// a check: true when the value is exactly the expected one, type included
console.log("price is 40:", price === 40);
price: 40 number
price is 40: true
WhenTry
the bug is somewhere in a long programhalve with prints
the program crashescut it down to the smallest example
you are sure it should worktest each assumption with one print
you are stuckexplain it aloud, line by line; take a break

The story: One line, proved

You stop guessing. You write down what you believe the script does, line by line, and test each belief against what is really there. One belief is wrong: you assumed a total started at zero, and it did not.

You cut the problem down until only four lines are left, and the fault sits in plain view. One small change, and every lamp on Chandler Street reads 310.

The foreman shakes your hand. Corin studies your notes. "You wrote everything down," he says, as if it were a trick. "Every time," says Ilse.

Reagents gathered: bug, assumption, smallest example, trace table, rubber duck.

Sources