Introduction
Debugging is how you find and fix problems in your JavaScript code. Browsers come with powerful tools that show errors, let you inspect variables, set breakpoints, step through code, and track performance.
1. The Console – Your First Debugger
console.log("Hello");
console.error("Something went wrong");
console.warn("Warning message");
Check the console in DevTools: F12 → Console tab
2. Checking Errors
JavaScript errors appear in red in the console with the exact file and line number.
// Example error:
Uncaught ReferenceError: x is not defined
3. Breakpoints
Breakpoints pause code execution so you can inspect variables and flow. In DevTools → Sources tab, click on a line number.
function calc(a, b) {
return a + b;
}
calc(5, 10);
4. debugger Keyword
Forcing a breakpoint in your code:
function test() {
debugger; // DevTools will pause here
console.log("Running...");
}
5. Inspecting Variables
let user = { name: "Kaloyan", age: 12 };
console.log(user);
Objects expand inside DevTools for deeper inspection.
6. Watch Expressions
In DevTools, you can add variables to “Watch” to monitor their values at runtime.
7. Step-by-Step Execution
- Step Over – run next line
- Step Into – jump inside function
- Step Out – exit current function
8. Network Tab
Debug API calls and check request/response data.
fetch("/api/user")
.then(r => r.json())
.then(console.log);
9. Performance Profiling
Find slow functions or laggy rendering.
10. Memory Debugging
Detect memory leaks via heap snapshots (used in long-running SPAs).
11. Common Debugging Tips
- Check console errors first
- Add logs to see where code breaks
- Use breakpoints for deeper inspection
- Check the Network tab for API failures
- Validate input before using it
- Use
try/catchto capture exceptions
12. try/catch Example
try {
let x = y + 2; // y is undefined
} catch (err) {
console.error("Caught error:", err);
}
Summary
- Console logs help track bugs
- DevTools breakpoints pause and inspect code
- Use debugger keyword for forced pauses
- Network tab helps debug API calls
- Performance tools detect slow code
- Error messages point directly to the problem