From Zero to Senior · The LabالعربيةGitHub

Chapter 14

Reading Errors and Debugging

8 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • read an error message and find exactly where the problem is
  • recognise the three most common kinds of error
  • follow a stack trace back to the real cause
  • find bugs that give no error at all, with console.log and the debugger
  • use a calm, step-by-step method that works for any bug

Examples

14.1 Anatomy of an error message

Here is a small program with a typo, and what Node.js says when you run it:

reference.js⤓ File
const score = 10;
console.log(scor);
Recorded output$ node reference.js
reference.js:2
console.log(scor);
            ^

ReferenceError: scor is not defined
    at Object.<anonymous> (reference.js:2:13)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

14.2 The three errors you will meet most

You used a name that JavaScript does not know, as above. The cause is almost always a typo, a variable used outside its scope (Chapter 10), or something used before it was created.

type.js⤓ File
const user = undefined;
console.log(user.name);
Recorded output$ node type.js
type.js:2
console.log(user.name);
                 ^

TypeError: Cannot read properties of undefined (reading 'name')
    at Object.<anonymous> (type.js:2:18)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

This is the most common error in all of JavaScript. You tried to read name from undefined, which has no properties. In real programs, user is undefined because a find found nothing, a server returned no data, or a property name was misspelled. The question to ask is: “why is this value undefined, when I expected an object?”

syntax.js⤓ File
const prices = [10, 20, 30;
console.log(prices);
Recorded output$ node syntax.js
syntax.js:1
const prices = [10, 20, 30;
                          ^

SyntaxError: Unexpected token ';'
    at wrapSafe (node:internal/modules/cjs/loader:1713:18)
    at Module._compile (node:internal/modules/cjs/loader:1755:20)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

14.3 Stack traces: how did we get here?

In bigger programs, functions call functions that call other functions. When an error happens deep inside, Node.js prints a stack trace: the path of calls that led to the error.

stack.js⤓ File
function getCity(user) {
  return user.address.city;
}

function welcome(user) {
  return `Hello from ${getCity(user)}!`;
}

console.log(welcome({ name: "Sara" }));
Recorded output$ node stack.js
stack.js:2
  return user.address.city;
                      ^

TypeError: Cannot read properties of undefined (reading 'city')
    at getCity (stack.js:2:23)
    at welcome (stack.js:6:24)
    at Object.<anonymous> (stack.js:9:13)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

14.4 Bugs without errors

The hardest bugs do not produce any error. The program runs and gives the wrong answer:

average-bug.js⤓ File
// The average of 10, 20 and 30 should be 20…
function average(numbers) {
  let total = 0;
  for (let i = 1; i < numbers.length; i++) {
    total = total + numbers[i];
  }
  return total / numbers.length;
}

console.log(average([10, 20, 30]));
Recorded output$ node average-bug.js
16.666666666666668

No red text, but 16.67 is not 20. When nothing tells you where the problem is, you make the program tell you. The simplest tool is console.log: print the values you are unsure about, at the moments you are unsure about them.

average-trace.js⤓ File
function average(numbers) {
  let total = 0;
  for (let i = 1; i < numbers.length; i++) {
    console.log("i =", i, "number =", numbers[i], "total =", total);
    total = total + numbers[i];
  }
  console.log("final total:", total);
  return total / numbers.length;
}

console.log(average([10, 20, 30]));
Recorded output$ node average-trace.js
i = 1 number = 20 total = 0
i = 2 number = 30 total = 20
final total: 50
16.666666666666668

Now the bug is obvious: the loop starts at i = 1, so it never adds the first number, 10. The total is 50 instead of 60. This is the trace table from Chapter 2, written by the computer. Fix the cause, here by using for…of, which cannot skip the first item, and test again, including an unusual case:

average-fixed.js⤓ File
function average(numbers) {
  let total = 0;
  for (const number of numbers) {
    total = total + number;
  }
  return total / numbers.length;
}

console.log(average([10, 20, 30]));
console.log(average([7]));
Recorded output$ node average-fixed.js
20
7

Now the bug is obvious: the loop starts at i = 1, so it never adds the first number, 10. The total is 50 instead of 60. This is the trace table from Chapter 2, written by the computer. Fix the cause, here by using for…of, which cannot skip the first item, and test again, including an unusual case:

console.js⤓ File
const cart = [
  { name: "Book", price: 25, quantity: 1 },
  { name: "Sticker", price: 3, quantity: 2 },
];

console.log("Items in cart:", cart.length);
console.table(cart);
console.error("Something is wrong here!");
Recorded output$ node console.js
Items in cart: 2
┌─────────┬───────────┬───────┬──────────┐
│ (index) │ name      │ price │ quantity │
├─────────┼───────────┼───────┼──────────┤
│ 0       │ 'Book'    │ 25    │ 1        │
│ 1       │ 'Sticker' │ 3     │ 2        │
└─────────┴───────────┴───────┴──────────┘
Something is wrong here!

Practice projects

Project 14.1 · Easy

The greeting that will not start

The program crashes before it prints anything. Read the error message and fix it with a single character.

You will practise: reading an error message from top to bottom: the line, the caret, the type and the description.

Steps
  1. Find the type of error. A ReferenceError means “I do not know this name”.
  2. Find the line and the caret ^: they point at the exact name JavaScript could not find.
  3. Compare that name, letter by letter, with the variable you created at the top. JavaScript is case-sensitive.
  4. Fix it, run the program again, and make sure the output below appears.

Hint: most errors you will ever meet are typos. Your editor can help: when you click on a variable, it highlights every place with the same name. A name that does not light up is a typo.

Solution
greet-bug.js⤓ File
const firstName = "Sara";
const visits = 3;

function welcome(person, count) {
  const message = `Welcome back, ${person}! visit #${count}`;
  return message;
}

console.log(welcome(firstname, visits));
Recorded output$ node greet-bug.js
greet-bug.js:9
console.log(welcome(firstname, visits));
                    ^

ReferenceError: firstname is not defined
    at Object.<anonymous> (greet-bug.js:9:21)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49
greet-fixed.js⤓ File
const firstName = "Sara";
const visits = 3;

function welcome(person, count) {
  const message = `Welcome back, ${person}! visit #${count}`;
  return message;
}

console.log(welcome(firstName, visits));
Recorded output$ node greet-fixed.js
Welcome back, Sara! visit #3

Project 14.2 · Medium

The checkout that cannot add

No error at all, but the total is nonsense. Find the two bugs hiding in five lines.

You will practise: bugs without errors, tracing values with console.log, the difference between text and numbers, and off-by-one loops.

Steps
  1. Read the wrong total carefully. Numbers stuck together like 01204535 are a clue: something is joining text, not adding numbers.
  2. Add console.log(i, list[i], typeof list[i]) inside the loop and run again.
  3. Bug 1: the prices are strings, so + glues them. Convert each one with Number(…).
  4. Bug 2: the last line of your trace shows i equal to 3 and the value undefined. The array has no item 3. Change <= to <.
  5. Remove your console.log lines, run once more, and check the result by hand: 120 + 45 + 35 = 200.

Hint: NaN (“not a number”) spreads like a stain: any sum that touches it becomes NaN. When you see it, look for the first undefined or text that went into a calculation.

Solution
cart-bug.js⤓ File
// Prices arrive as text, as they do from a form or a file
const prices = ["120", "45", "35"];
const discount = 20;

function total(list) {
  let sum = 0;
  for (let i = 0; i <= list.length; i++) {
    sum = sum + list[i];
  }
  return sum;
}

const before = total(prices);
console.log("Total:", before);
console.log("After discount:", before - discount);
Recorded output$ node cart-bug.js
Total: 01204535undefined
After discount: NaN
cart-fixed.js⤓ File
// Prices arrive as text, as they do from a form or a file
const prices = ["120", "45", "35"];
const discount = 20;

function total(list) {
  let sum = 0;
  for (let i = 0; i < list.length; i++) {
    sum = sum + Number(list[i]);
  }
  return sum;
}

const before = total(prices);
console.log("Total:", before);
console.log("After discount:", before - discount);
Recorded output$ node cart-fixed.js
Total: 200
After discount: 180

Project 14.3 · Challenge

The order that breaks the list

The first order prints, then the program dies. Follow the stack trace back to the cause, and fix it so every order prints.

You will practise: reading a stack trace, finding bad data rather than bad code, and guarding against missing values.

Steps
  1. Read the stack from the top: the crash is in label, which was called by printAll, which was called from line 17.
  2. The message says it could not read name of undefined. So in order.customer.name, the undefined is order.customer.
  3. One order printed before the crash, so the problem is the second order. Look at the data: order 2 has no customer.
  4. Decide what should happen. Here a missing customer is a guest, so add an if (!order.customer) at the start of label and return a “guest” line.
  5. Run again. All three orders should print, and the program should finish normally.

Hint: the line that crashes is often not the line that is wrong. The code in label was fine; the data was not what it expected. Real data from users and servers is always missing something, so professionals check before they read deep inside an object.

Solution
orders-bug.js⤓ File
const orders = [
  { id: 1, customer: { name: "Omar" }, total: 40 },
  { id: 2, total: 15 },
  { id: 3, customer: { name: "Huda" }, total: 22 },
];

function label(order) {
  return `#${order.id} ${order.customer.name}: ${order.total}`;
}

function printAll(list) {
  for (const order of list) {
    console.log(label(order));
  }
}

printAll(orders);
Recorded output$ node orders-bug.js
#1 Omar: 40
orders-bug.js:8
  return `#${order.id} ${order.customer.name}: ${order.total}`;
                                        ^

TypeError: Cannot read properties of undefined (reading 'name')
    at label (orders-bug.js:8:41)
    at printAll (orders-bug.js:13:17)
    at Object.<anonymous> (orders-bug.js:17:1)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49
orders-fixed.js⤓ File
const orders = [
  { id: 1, customer: { name: "Omar" }, total: 40 },
  { id: 2, total: 15 },
  { id: 3, customer: { name: "Huda" }, total: 22 },
];

function label(order) {
  if (!order.customer) {
    return `#${order.id} (guest): ${order.total}`;
  }
  return `#${order.id} ${order.customer.name}: ${order.total}`;
}

function printAll(list) {
  for (const order of list) {
    console.log(label(order));
  }
}

printAll(orders);
Recorded output$ node orders-fixed.js
#1 Omar: 40
#2 (guest): 15
#3 Huda: 22

Exercises

Exercise 14.1 · Easy

Each line below has one bug. Predict the error type, then check with Node: console.log("hi), const a = 1; a = 2;, let list; list.push(1);, consol.log(5);
The book's short answer
SyntaxError, TypeError (assignment to a constant), TypeError (list is undefined), ReferenceError.
Show the solution
predict-errors.js⤓ File
Runs with Node.js: node predict-errors.js
// Each snippet has one bug. Our predictions are in the comments; the program runs each one and prints the real error.
// vm runs a piece of code given as text, so one error does not stop the whole program.
const vm = require("node:vm");

const snippets = [
  ['console.log("hi)', "SyntaxError"], // the closing quote is missing
  ["const a = 1; a = 2;", "TypeError"], // a const cannot be given a new value
  ["let list; list.push(1);", "TypeError"], // list is undefined, and undefined has no push
  ["consol.log(5);", "ReferenceError"], // no variable is called consol
];

for (const [code, predicted] of snippets) {
  try {
    vm.runInNewContext(code, { console });
    console.log(`${code}  ->  no error`);
  } catch (error) {
    const mark = error.name === predicted ? "✓" : "✗";
    console.log(`${mark} ${code}  ->  ${error.name}: ${error.message}`);
  }
}
Recorded output$ node predict-errors.js
✓ console.log("hi)  ->  SyntaxError: Invalid or unexpected token
✓ const a = 1; a = 2;  ->  TypeError: Assignment to constant variable.
✓ let list; list.push(1);  ->  TypeError: Cannot read properties of undefined (reading 'push')
✓ consol.log(5);  ->  ReferenceError: consol is not defined

Exercise 14.2 · Easy

Fix stack.js in two ways: by giving the user an address, and by making getCity return "somewhere" when there is no address.
The book's short answer
Add address: { city: "Alexandria" } to the user, or write return user.address ? user.address.city : "somewhere";
Show the solution
stack-fixed.js⤓ File
// Fix 1: give the user an address.
function getCity(user) {
  return user.address.city;
}

function welcome(user) {
  return `Hello from ${getCity(user)}!`;
}

console.log(welcome({ name: "Sara", address: { city: "Alexandria" } }));

// Fix 2: getCity copes with a user who has no address.
function getCitySafely(user) {
  return user.address ? user.address.city : "somewhere";
}

function welcomeSafely(user) {
  return `Hello from ${getCitySafely(user)}!`;
}

console.log(welcomeSafely({ name: "Sara" }));
console.log(welcomeSafely({ name: "Adam", address: { city: "Gaza" } }));

// The short way to write the same thing, with ?. (optional chaining) and ??:
console.log(({ name: "Huda" }).address?.city ?? "somewhere");
Recorded output$ node stack-fixed.js
Hello from Alexandria!
Hello from somewhere!
Hello from Gaza!
somewhere

Exercise 14.3 · Medium

Put a breakpoint inside addToCart in the shop from Chapter 12. Click “Add to cart” and step through the function, watching cart change.
The book's short answer
Click the line number inside addToCart in the Sources panel, click the button on the page, and use Step.
Show the solution
  1. Open shop.html in the browser and open DevTools (F12), then the Sources panel.
  2. In shop.js, click the line number of the first line inside addToCart. A blue marker appears: that is the breakpoint. (In this copy, the line debugger; does the same job, so you can skip this step.)
  3. Click "Add to cart" on any product. The page freezes and the line is highlighted.
  4. In the Scope pane, open cart: it is still empty on the first click.
  5. Press Step over (F10) line by line. After cart.push(...), cart has one item; on a second click on the same product, line.quantity++ runs instead.
  6. Press Resume (F8) to let the page run again.
shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="../../../ch12/examples/shop.css">
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section id="products"></section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
  { id: 4, name: "Bit T-shirt", price: 15 },
];

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  // With DevTools open, the browser pauses here, as if you had clicked this line number in the Sources panel.
  // Hover over cart to see its value, then press "Step over" (F10) line by line and watch it change.
  debugger;
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

renderProducts();
renderCart();

Exercise 14.4 · Medium

This function should count the words longer than three letters, but returns the wrong number. Find the bug with console.log: function count(words) { let n = 0; for (const w of words) { if (w.length > 3) n = 1; } return n; }
The book's short answer
n = 1 should be n = n + 1 (or n++).
Show the solution
count-words.js⤓ File
const words = ["code", "is", "fun", "and", "useful", "always"];

// The buggy version, with a labelled console.log inside the loop.
function countBuggy(list) {
  let n = 0;
  for (const w of list) {
    if (w.length > 3) n = 1;
    console.log(`  w = "${w}", n = ${n}`);
  }
  return n;
}

console.log(`Buggy: ${countBuggy(words)}`);
// The log shows n stuck at 1 after "code", "useful" and "always": n = 1 sets it, it never adds.

function count(list) {
  let n = 0;
  for (const w of list) {
    if (w.length > 3) n++; // the fix: add 1 each time
  }
  return n;
}

console.log(`Fixed: ${count(words)}`);
Recorded output$ node count-words.js
  w = "code", n = 1
  w = "is", n = 1
  w = "fun", n = 1
  w = "and", n = 1
  w = "useful", n = 1
  w = "always", n = 1
Buggy: 1
Fixed: 3

Exercise 14.5 · Challenge

Take a program from an earlier chapter that works. Ask a friend to add one small bug without telling you where. Find it using only the method in Section 14.6, and write down each step you took.
The book's short answer
There is no single answer; the important part is writing down each step of the method.
Show the solution

Bug hunt log

The program: queue-with-bug.js, a copy of queue.js from Chapter 9 with one bug added by a friend. I followed the method of Section 14.6 and wrote down each step.

  1. Reproduce it. node queue-with-bug.js prints Total: 50 every time. Working by hand: 10 + 6 + 0 + 6 + 10 + 10 + 0 = 42.
  2. Read the error. There is no error message: the program runs, but the answer is wrong. It is a bug without an error (Section 14.4), so the next tool is console.log.
  3. Form a guess. 50 is 8 more than 42. Two visitors, aged 9 and 70, should pay 6 each; if they both paid 10, the total would be exactly 4 + 4 = 8 more. My guess: the child and senior rule never matches.
  4. Test the guess. queue-traced.js prints each age with its price, without changing the logic. Ages 9 and 70 get 10, and every other price is right, so the guess is confirmed: the bug is in that one condition.
  5. Fix the cause. The condition says age < 13 && age >= 65: younger than 13 and at least 65 at the same time, which no one is. The rule needs ||. queue-fixed.js prints 42. Unusual cases checked: ages 12, 13, 64 and 65.
queue-fixed.js⤓ File
const queue = [34, 9, 2, 70, 16, 41, 3];

let total = 0;
let freeTickets = 0;

for (const age of queue) {
  let price;
  if (age < 4) {
    price = 0;
    freeTickets++;
  } else if (age < 13 || age >= 65) { // the fix: || (either), not && (both)
    price = 6;
  } else {
    price = 10;
  }
  total = total + price;
}

console.log(`Free tickets: ${freeTickets}`);
console.log(`Total: ${total}`);
Recorded output$ node queue-fixed.js
Free tickets: 2
Total: 42
queue-traced.js⤓ File
// Step 4 of the method: test the guess with labelled console.log lines, without changing the logic.
const queue = [34, 9, 2, 70, 16, 41, 3];

let total = 0;

for (const age of queue) {
  let price;
  if (age < 4) {
    price = 0;
  } else if (age < 13 && age >= 65) {
    price = 6;
  } else {
    price = 10;
  }
  console.log(`age = ${age}, price = ${price}`);
  total = total + price;
}

console.log(`Total: ${total}`);
Recorded output$ node queue-traced.js
age = 34, price = 10
age = 9, price = 10
age = 2, price = 0
age = 70, price = 10
age = 16, price = 10
age = 41, price = 10
age = 3, price = 0
Total: 50
queue-with-bug.js⤓ File
// A friend added one bug to queue.js from Chapter 9. The total should be 42; the program prints 50.
const queue = [34, 9, 2, 70, 16, 41, 3];

let total = 0;
let freeTickets = 0;

for (const age of queue) {
  let price;
  if (age < 4) {
    price = 0;
    freeTickets++;
  } else if (age < 13 && age >= 65) {
    price = 6;
  } else {
    price = 10;
  }
  total = total + price;
}

console.log(`Free tickets: ${freeTickets}`);
console.log(`Total: ${total}`);
Recorded output$ node queue-with-bug.js
Free tickets: 2
Total: 50