JavaScript Debugging

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

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

12. try/catch Example

try {
  let x = y + 2; // y is undefined
} catch (err) {
  console.error("Caught error:", err);
}
    

Summary