Debugging in JavaScript


Debugging is the process of finding and fixing errors (bugs) in your JavaScript code. Mastering debugging helps improve your coding skills and speed up development.



Why Debugging Matters

  • Helps locate and fix runtime errors
  • Improves code quality
  • Essential for working with large or asynchronous codebases


Common JavaScript Debugging Tools

Tool Description
console.log() Logs values to the console
Chrome DevTools Built-in browser tool for inspecting & debugging
debugger statement Pauses code execution at a specific line
Breakpoints Let you pause and inspect code in DevTools
Stack trace Shows call history leading to an error


1. Using console.log()

Log values, functions, objects, or flow tracking:

const num = 5;
console.log("Number is:", num);

Use it to trace bugs or confirm if a function is being called.



2. The debugger Statement

The debugger keyword stops the execution and opens the browser's debugger.

function testDebug(num) {
  debugger; // Execution pauses here
  return num * 2;
}

testDebug(10);

Open Chrome DevTools (F12) > Sources tab > Reload and watch the code pause at debugger.



3. Chrome DevTools Features

  • Console Tab – View logs and errors
  • Sources Tab – View and step through code
  • Network Tab – Check API calls, status, and timing
  • Elements Tab – Inspect and edit HTML/CSS
  • Breakpoints – Set to pause code on specific lines or events

Tip: Use the "Pause on Exceptions" option to stop when an error occurs.



4. Error Stack Traces

When an error occurs, JavaScript prints a stack trace.

function a() {
  b();
}

function b() {
  throw new Error("Something went wrong!");
}

a();

The console shows:

Error: Something went wrong!
    at b (...)
    at a (...)

You can trace exactly where the error happened.



5. Network Debugging (APIs)

Use the Network tab in DevTools to check:

  • API status (e.g. 200, 404)
  • Response time
  • Returned data
  • Errors (like CORS or failed fetch)


6. VS Code Debugging

If you're using Visual Studio Code:

  • Set breakpoints in the editor
  • Press F5 to start debugging
  • Use the Debug Panel to watch variables and call stack