JS Debugging
In this page:
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
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
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
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
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
// 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: