JS Debugging
In this page:
console.log(value);
debugger;
console.error(value);
console.table(data);
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
// Call `console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }])`
// Call `console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }])`
console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }]);
// Print "Something went wrong" to the console as an error
// Print "Something went wrong" to the console as an error
console.error("Something went wrong");
// Print "This is deprecated" to the console as a warning
// Print "This is deprecated" to the console as a warning
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
- Leaving
console.logordebuggerstatements in production code. - Logging an object and trusting what the console shows later, since expanding it shows its current values, not the values at log time.
- Ignoring the stack trace in the console error, which shows the file and line.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: