Error handling and debugging in JavaScript – common error types, try/catch, breakpoints, and a few practical habits that save time.
Understanding errors in JavaScript
Errors happen. A typo, an undefined variable, calling something that is not a function – recognising the type of error is the first step towards fixing it.
Common error types
- Syntax error: a typo or mistake in the code’s syntax.
- Reference error: referencing a variable that has not been declared.
- Type error: an operation on the wrong data type.
The console: your first debugging tool
The browser console shows errors and lets you run JavaScript and inspect variables.
Example
console.log("Hello, debugging world!");
Strategic console.log() calls help you track down where things go wrong.
Try…catch: handling errors gracefully
The try...catch statement lets you attempt a block of code and handle any error that is thrown.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}
Example
try {
let result = someUndefinedFunction();
console.log(result);
} catch (error) {
console.error("Caught an error:", error);
}
Throwing custom errors
Use throw to raise your own error when something is not valid.
Example
function calculateArea(radius) {
if (radius <= 0) {
throw "Radius must be positive";
}
return Math.PI * radius * radius;
}
try {
let area = calculateArea(-1);
console.log(area);
} catch (error) {
console.error("Error:", error);
}
Debugging with breakpoints
Browser developer tools let you pause execution at a specific line, inspect variables, and step through code line by line.
Setting breakpoints
- Open the browser’s developer tools.
- Go to the Sources tab.
- Find your JavaScript file.
- Click on the line number where you want to pause execution.
The debugger statement
Put debugger in your code to create a breakpoint. When developer tools are open, execution pauses there.
Example
function problematicFunction() {
debugger; // Execution will pause here
// More code...
}
Using stack traces
When an error occurs, JavaScript prints a stack trace – a list of function calls that led to the error. Read it from the top to find where things started going wrong.
Best practices for debugging
- Read the error message: start with the message and stack trace before changing code at random.
- Simplify the problem: break complex functions into smaller parts.
- Check the basics: typos and syntax mistakes cause more bugs than you might expect.
- Use logging wisely: a few well-placed
console.log()calls beat logging everything. - Use developer tools: breakpoints, watch expressions, and the console are there for a reason.
Every developer hits errors. What matters is having a method for finding and fixing them – and getting faster at it with practice.

