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.
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, likeTypeError.message: a human description, likeCannot 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
| Type | Means | Typical cause |
|---|---|---|
SyntaxError | The code is not valid JavaScript | A missing bracket, or JSON.parse on bad text |
ReferenceError | A name does not exist | A typo in a variable name, or using let before its line |
TypeError | A value is the wrong kind for the operation | Calling something that is not a function, reading a property of undefined |
RangeError | A number is outside the allowed range | new 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 each line of code to the error it throws.
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.
Press Run (⌘ Enter) to see what happens.Three rules make error handling work instead of hiding bugs:
- Throw
Errorobjects, not strings.throw "bad input"works, but a string has nonameand nostack, so you lose the most useful debugging information. - Only catch what you can handle. A
catchthat 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 withthrow err. - Keep
tryblocks small. Wrap the one call that can fail, not fifty lines, so you know which line thecatchis about.
See the difference rule 1 makes:
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.
What does this print?
function check() {
try {
return "try";
} finally {
console.log("finally");
}
}
console.log(check());catch is the most likely to hide a bug?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.
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 bottom frame is where this chain of calls started: the click handler.
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 tookTwo 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 this debugging routine in order.
- Tap the steps below in the right order.
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.
- 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
Errorwith its ownname, so callers can check it withinstanceof. - 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.