Skip to content

Lesson 16 of 50JavaScript in depth

Errors and Debugging

Read error messages and stack traces, throw and catch errors on purpose, write custom errors, and find bugs with the console and breakpoints.

16 min read0/4 questions

Every developer spends a large part of their day with code that does not work yet. The difference between a beginner and an experienced developer is not that the experienced one makes fewer mistakes. It is that they read the error message carefully, know where to look, and have a routine for narrowing down the problem instead of changing things at random. This lesson covers both sides of errors: the ones JavaScript throws at you, and the ones you throw on purpose to stop bad data in its tracks. Then it walks through the tools for finding bugs: the console, the debugger and a step by step routine you can use on any problem.

What an error is

When JavaScript hits something it cannot do, it creates an Error object and throws it. Throwing stops the current function immediately. If nothing catches the error, it travels up through every function that called this one, and if it reaches the top, the program (or that piece of a web page's script) stops and the message appears in the console.

Every error object has three properties you will use:

  • name: the kind of error, like TypeError.
  • message: a human description, like Cannot read properties of undefined (reading 'name').
  • stack: the stack trace, a list of the function calls that were active when the error happened.

The built-in error types

TypeMeansTypical cause
SyntaxErrorThe code is not valid JavaScriptA missing bracket, or JSON.parse on bad text
ReferenceErrorA name does not existA typo in a variable name, or using let before its line
TypeErrorA value is the wrong kind for the operationCalling something that is not a function, reading a property of undefined
RangeErrorA number is outside the allowed rangenew Array(-1), or a recursive function that never stops

TypeError: Cannot read properties of undefined is the error you will see more than all the others put together. It means you wrote something.property and something was undefined. The fix is never in that line itself: the real question is why the value was undefined, which usually means a typo, a missing return, or data that has not loaded yet.

Match the pairs0/5 matched

Match each line of code to the error it throws.

Choose an item, then its match on the other side.

throw, try, catch, finally

You can throw your own errors with the throw keyword. This is how a function says "I cannot do what you asked with this input", instead of returning a wrong answer that causes trouble later.

To handle an error, wrap the risky code in try. If anything inside throws, JavaScript jumps straight to the catch block, which receives the error. An optional finally block runs afterwards no matter what: after success, after a caught error, and even after a return.

JavaScript
function parseQuantity(text) { const n = Number(text); if (!Number.isInteger(n) || n < 1) { throw new RangeError(`Quantity must be a whole number of 1 or more, got "${text}"`); } return n;} for (const input of ["3", "two", "-1"]) { try { const qty = parseQuantity(input); console.log("ok:", qty); } catch (err) { console.log(`${err.name}: ${err.message}`); } finally { console.log("checked", input); }}
Output
Press Run (⌘ Enter) to see what happens.

Three rules make error handling work instead of hiding bugs:

  1. Throw Error objects, not strings. throw "bad input" works, but a string has no name and no stack, so you lose the most useful debugging information.
  2. Only catch what you can handle. A catch that logs and carries on as if nothing happened (a "swallowed" error) turns a loud, findable crash into a quiet wrong result. If you cannot fix the problem at this level, let it travel up, or re-throw it with throw err.
  3. Keep try blocks small. Wrap the one call that can fail, not fifty lines, so you know which line the catch is about.

See the difference rule 1 makes:

JavaScript
try { throw "bad input";} catch (err) { console.log(typeof err, err.name, err.stack); // a bare string: no name, no stack} try { throw new Error("bad input");} catch (err) { console.log(typeof err, err.name, typeof err.stack); // a real Error object console.log(err instanceof Error);}
Output
Press Run (⌘ Enter) to see what happens.

If you do not need the error object, you can leave it out: catch { ... } is valid modern JavaScript. For promises and await, the same try/catch works once you await the call, as the async lessons show.

Predict the outputJavaScript

What does this print?

function check() {
try {
  return "try";
} finally {
  console.log("finally");
}
}
console.log(check());
Need a nudge? Hints walk you through it.
Quick check
Which catch is the most likely to hide a bug?
Need a nudge? A hint rules out a wrong answer.

Custom errors

When your code can fail in several different ways, give each a custom error class. Callers can then check the kind of error with instanceof instead of searching the message text, which breaks the moment someone rewords it.

JavaScript
class ValidationError extends Error { constructor(field, message) { super(message); this.name = "ValidationError"; this.field = field; }} function validateSignup({ email, age }) { if (!email.includes("@")) throw new ValidationError("email", "Enter a valid email address"); if (age < 13) throw new ValidationError("age", "You must be 13 or older"); return true;} function saveSettings(raw) { try { return JSON.parse(raw); } catch (err) { // Wrap the low-level error, but keep it as the cause throw new Error("Settings file is corrupted", { cause: err }); }} try { validateSignup({ email: "ada.example.com", age: 30 });} catch (err) { if (err instanceof ValidationError) { console.log(`Show next to the ${err.field} field: ${err.message}`); } else { throw err; // not ours: let it travel up }} try { saveSettings("{ broken");} catch (err) { console.log(err.message, "| caused by:", err.cause.name);}
Output
Press Run (⌘ Enter) to see what happens.

Setting this.name makes the error print as ValidationError instead of plain Error. The cause option (ES2022) lets you wrap a low-level error in a clearer one without losing the original: the user sees "Settings file is corrupted", and the developer can still read the exact JSON problem in err.cause. Class syntax (extends, super) is covered in the classes lesson.

Reading a stack trace

A stack trace lists the functions that were running when the error was thrown, most recent first. Each line is a frame: a function name, then the file, line and column. Here is a typical one from a browser console:

TypeError: Cannot read properties of undefined (reading 'price')
    at lineTotal (cart.js:12:24)
    at Array.map (<anonymous>)
    at cartTotal (cart.js:18:30)
    at renderCart (app.js:44:17)
    at HTMLButtonElement.onClick (app.js:61:5)

Read it top to bottom. The first line is the error and its message. The next line is where it happened: inside lineTotal, line 12 of cart.js, column 24. Each line below is who called that. So the user clicked a button, which called renderCart, which called cartTotal, which ran map, which called lineTotal, which tried to read .price of something undefined.

The call stack when the error is thrown
  1. lineTotal(item)cart.js:12, reads item.price
  2. Array.mapbuilt in, calls lineTotal per item
  3. cartTotal(cart)cart.js:18
  4. renderCart()app.js:44
  5. onClickapp.js:61, the button handler

The bottom frame is where this chain of calls started: the click handler.

1/4

Click the file link in the console and the browser opens that exact line. If the top frame is inside a library, scroll down to the first frame in your own code: that is almost always where the wrong value came from.

The console, beyond log

console.log is the first debugging tool everyone learns, and it stays useful forever. Its relatives are worth knowing:

console.log("cart", cart);          // label your logs, or you will not know which is which
console.error("Payment failed", err); // red, with a stack trace, counts as an error
console.warn("Price missing for", item.id); // yellow warning
console.table(users);               // an array of objects as a sortable table
console.group("checkout"); /* ... */ console.groupEnd(); // indent related logs
console.time("load"); /* ... */ console.timeEnd("load"); // how long something took

Two habits help. Log objects as their own argument (console.log("user", user)) rather than inside a template literal, which turns them into [object Object]. And remove debugging logs before you commit; a linter rule like ESLint's no-console can remind you.

Breakpoints and the debugger

Logging means guessing in advance what you want to see. A breakpoint pauses the program at a line so you can look at everything: every variable, the whole call stack, and what happens as you move one line at a time.

In Chrome or Edge, open DevTools (F12, or Cmd+Option+I on a Mac), go to the Sources panel, open your file and click a line number. A blue marker appears. Do the thing that triggers the code, and the page freezes on that line. From there:

  • Scope shows every variable's current value. Hover over a variable in the code to see it too.
  • Step over runs the current line and stops at the next one. Step into follows a function call inside. Step out finishes the current function.
  • Watch lets you type any expression, like cart.items.length, and see it update as you step.
  • Right-click a line number for a conditional breakpoint, which only pauses when an expression is true, such as item.price === undefined. This is how you catch the one bad item in a list of a thousand.

You can also write the debugger; statement in your code. When DevTools is open, execution pauses there just like a breakpoint; when it is closed, the statement does nothing. Firefox and Safari have the same tools under slightly different names, and VS Code can set breakpoints in Node.js code (run with node --inspect, or use its built-in JavaScript debugger).

A debugging routine

When something is broken, resist the urge to change code at random. Work through the same steps every time:

Put it in order6 steps

Put this debugging routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Two extra tricks help when you are stuck. Halve the problem: comment out or skip half the code and see whether the bug remains, then repeat with the half that still fails. And explain it out loud, line by line, to a colleague or even a rubber duck on your desk. Saying what each line should do often reveals the one that does not.

Key terms
throw
Stop the current function and send an error up to whoever called it.
try / catch / finally
Run risky code, handle an error if one is thrown, and always run clean-up code.
custom error
A class that extends Error with its own name, so callers can check it with instanceof.
stack trace
The list of active function calls when an error was thrown, most recent first.
breakpoint
A marker that pauses the program at a line so you can inspect every variable.
debugger statement
debugger; in code pauses execution there when DevTools is open.