← Back to JavaScript Course | Chapter 12: Reference & Interview | Lesson 2 of 9

JS Debugging

What Is Debugging

Debugging is the process of methodically finding why code isn't behaving as expected, usually by inspecting values at different points in execution rather than guessing at the cause.

Example: What Is Debugging

javascript
const value = 5 + "5"; // unexpected result?
console.log(value); // inspect it directly instead of guessing

console Methods

console.log() prints values for a quick look, while console.table(), console.error(), and console.warn() format or categorize output for easier scanning in more complex debugging sessions.

Example: console Methods

javascript
console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }]);
console.error("Something went wrong");
console.warn("This is deprecated");

Breakpoints and Debugger

A breakpoint pauses execution at a specific line so you can inspect variables and step through code one statement at a time in the browser or Node debugger, rather than relying only on print statements.

Example: Breakpoints and Debugger

javascript
function calculate(a, b) {
  debugger; // pauses execution here in dev tools
  return a + b;
}
calculate(2, 3);

Handling Errors While Debugging

When debugging error-prone code, catch and log the full error object (not just its message) so you retain the stack trace showing exactly where and how the failure originated.

Example: Handling Errors While Debugging

javascript
try {
  JSON.parse("bad json");
} catch (error) {
  console.log(error); // log the full error object, not just error.message
}

Debugging Best Practices

Reproduce the bug with the smallest possible example, form a hypothesis about the cause, and verify it with a targeted check — this is faster than randomly changing code and rerunning.

Example: Debugging Best Practices

javascript
// Reproduce with the smallest example, then verify a hypothesis:
function add(a, b) { return a + b; }
console.log(add(2, "3")); // hypothesis: string coercion is happening
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.