Skip to content

Errors & Debugging

The Course
•
17 min study

There are three useful kinds of failure to distinguish. A syntax error means the code cannot be parsed, such as an unclosed quote. A runtime error happens while executing, such as reading an undeclared name. A logic error runs successfully but gives the wrong result.

Read the error's name and message, then inspect the indicated line and the line before it. Syntax mistakes are sometimes reported after their cause. For a logic error, write expected versus actual output and reduce the input to the smallest example that still fails. Inspect one changing value at a time with console.log.

A try block lets you handle an exception in catch. Catch a problem when you have a useful response: report invalid imported data, for example. Do not surround everything with an empty catch; that hides defects and makes a broken program look successful. throw new Error("message") deliberately reports a failure: new Error(...) creates an error value containing your message, and throw stops the current work and passes that error to a matching catch. In catch (error), error is a local name for the caught value; error.message reads its message. Without a matching catch, the editor reports the failure and stops that run.

Predict before running

The example throws on purpose and handles it. Which line is skipped? Replace the thrown error with a normal log and compare the order.

Predict, then run JavaScript
try {
  throw new Error("Missing topic");
  console.log("This line is skipped");
} catch (error) {
  console.log(error.message);
}

console.log("Ready for another attempt");
Check your prediction
Text
Missing topic
Ready for another attempt

Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.

Read a real error message

When a runtime error is not caught, the program stops and the output shows two things: the error's name (its kind) and its message (what went wrong), usually with the line where it happened. Two names come up constantly:

  • TypeError: a value is the wrong kind for what you did with it. The classic case is reading a property of undefined, for example sessions[1].minutes when there is no sessions[1].
  • ReferenceError: you used a name that was never declared, usually a typo such as totl for total.

This program catches both errors so you can read their parts. Predict each name before running it, then delete one try and its catch block (keep the line inside) and run again: the editor stops at that line and shows the same name and message.

Name and message JavaScript
const sessions = [{ topic: "Loops", minutes: 20 }];

try {
  console.log(sessions[1].minutes);
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}

try {
  const total = 20;
  console.log(totl + 5);
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}
Check your prediction
Text
TypeError
Cannot read properties of undefined (reading 'minutes')
ReferenceError
totl is not defined

Read the message from the end: (reading 'minutes') names the property, and "of undefined" says the value before the dot was undefined. So the question to ask is "why is sessions[1] undefined?", not "what is wrong with minutes?". Browsers word some messages differently (Firefox says sessions[1] is undefined), but the name is the same everywhere.

Find the first wrong step

A wrong final total is a symptom. Trace the intermediate values until the first mismatch appears. Text from a form is still text even when it looks numeric. Logging typeof alongside a value helps distinguish 20 from "20". Fix the conversion at the boundary instead of scattering conversions through every calculation.

Find the first wrong step JavaScript
const input = "20";
let total = 10;

console.log(typeof input);
console.log(total + input);
total += Number(input);
console.log(total);
Check your prediction
Text
string
1020
30

The plus operator concatenates when a string is involved. Converting a valid numeric input first makes the intended addition possible.

Reduce a failure to the first wrong value

Start debugging at the first value that differs from your expectation, rather than adding random edits near the final output. A program can fail by throwing, by choosing the wrong branch, or by calculating the wrong result while running normally. The last case needs a known expected answer.

A catch is a policy decision, not a way to make the program look successful. Catch a failure where you can produce a meaningful response. After a failed conversion or operation, avoid continuing as if a valid new value had been produced.

Inspect the intermediate calculation JavaScript
const count = 3;
const minutes = "20";

console.log("raw:", minutes);
console.log("joined:", minutes + count);
console.log("total:", Number(minutes) * count);
Check your prediction
Text
raw: 20
joined: 203
total: 60

The wrong result begins at the addition of text and a number. The final multiplication demonstrates the intended calculation. Keep a tiny input with a hand-computable answer while fixing the real function.

Failure should not overwrite good data JavaScript
let title = "Previous plan";

try {
  throw new Error("New plan unavailable");
  title = "New plan";
} catch (error) {
  console.log(error.message);
}

console.log(title);
Check your prediction
Text
New plan unavailable
Previous plan

The assignment after throw never runs. Preserving the previous title is different from returning a successful empty title. State the intended recovery behavior before deciding where to catch.

Try the rule on new inputs

Introduce one error at a time: a misspelled variable, a wrong operator and a property read on a missing item. For each, say whether the editor reports a named error or the program runs and prints a wrong value that only an expected-value check would catch. Remove temporary logs after the cause is understood.

Before you move on

Start from the first thing that looked wrong and make one guess about why. Add one console.log where you think the value goes wrong, rather than changing several lines at once. After the fix, keep the smallest failing input as a check.

Your turn

Exercise

Errors & Debugging: practice

minutesFor(sessions, topic) should return the minutes for a topic, or 0 when the topic is not in the list. Run the program: the first call works, then it stops with an error. Read the error's name and message, find the line that caused it, and repair minutesFor so the program prints:

Text
20
0
0
Your working space JavaScript
function minutesFor(sessions, topic) {
  const session = sessions.find(item => item.topic === topic);
  return session.minutes;
}

const plan = [
  { topic: "Loops", minutes: 20 },
  { topic: "Arrays", minutes: 30 }
];

try {
  console.log(minutesFor(plan, "Loops"));
  console.log(minutesFor(plan, "Objects"));
  console.log(minutesFor([], "Loops"));
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Hint 1: the idea

The message says something was undefined when the program tried to read minutes. Only one line in minutesFor reads minutes. What does find give back when nothing matches?

Hint 2: a first step

Add console.log(session); just before the return and run again. For "Loops" you will see a record; for "Objects" you will see undefined. That is the case to handle before the return.

Show one solution
JavaScript
function minutesFor(sessions, topic) {
  const session = sessions.find(item => item.topic === topic);

  if (session === undefined) {
    return 0;
  }

  return session.minutes;
}

const plan = [
  { topic: "Loops", minutes: 20 },
  { topic: "Arrays", minutes: 30 }
];

try {
  console.log(minutesFor(plan, "Loops"));
  console.log(minutesFor(plan, "Objects"));
  console.log(minutesFor([], "Loops"));
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
20
0
0

The original printed 20 and then TypeError: Cannot read properties of undefined (reading 'minutes'). find returns undefined when no item matches, and session.minutes then reads a property of undefined. Checking for undefined before the property read gives the missing case its own answer, and the same check covers an empty list. The try/catch stays useful: if a different bug appears later, it still reports the name and message instead of hiding them.

What you should be able to explain

  • What is the smallest input that reproduces your bug?
  • What did you expect, and at which step did reality differ?
  • After fixing it, what nearby case will you rerun?

Was this article helpful?

Your response is saved on this device.