JavaScript Debugging
Debugging is the process of finding and fixing errors in your code. Master essential debugging techniques, tools, and best practices to become a more effective developer.
How do you debug JavaScript?
Start with the browser console (F12): read the error message and the file and line it points to. Use console.log() to inspect values, or better, set a breakpoint in the Sources panel, or write debugger; in your code, to pause execution and step through it line by line while inspecting every variable.
console.log("total:", total);
console.table(users); // arrays of objects as a table
console.error("Failed:", err);
debugger; // pauses here when DevTools is openSyntaxError
Unexpected token ')'Invalid JavaScript syntax detected during parsing.
ReferenceError
x is not definedVariable or function not found in current scope.
TypeError
Cannot read property 'x' of nullOperation performed on wrong data type.
RangeError
Maximum call stack exceededValue outside valid range or infinite recursion.
Interactive Debugging Demo
Code Editor
<button id="buggy">Run buggy code</button>
<button id="fixed">Run fixed code</button>
<pre id="out"></pre>Preview
Console Methods
console.log()Basic output
console.table()Tabular data
console.time()Performance timing
Breakpoints
debugger;Code breakpoint
• Click line numbers in Sources tab
• Conditional breakpoints
Step Controls
• Step Over (F10)
• Step Into (F11)
• Step Out (Shift+F11)
• Continue (F8)
Error Handling Strategies
Try-Catch-Finally
try {
// Code that might throw an error
const result = riskyOperation();
return result;
} catch (error) {
// Handle the error
console.error('Error occurred:', error);
return null;
} finally {
// Always executes (cleanup)
cleanup();
}The finally block always runs, even if an error occurs.
Custom Error Types
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
function validateAge(age) {
if (age < 0) {
throw new ValidationError('Age cannot be negative');
}
}Create custom error types for better error categorization.
Common Debugging Scenarios
Undefined Variables
❌ console.log(user.profile.email); // Error if profile is undefined✅ console.log(user?.profile?.email); // Safe with optional chainingAsync Issues
❌ const data = fetch(url); // Returns Promise, not data✅ const data = await fetch(url).then(r => r.json());Scope Problems
❌ for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints 3, 3, 3
}✅ for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints 0, 1, 2
}Type Coercion
❌ "5" + 3 = "53" (string concatenation)✅ Number("5") + 3 = 8 (explicit conversion)Browser Developer Tools Guide
Essential DevTools Tabs
Console
- • View logs and errors
- • Execute JavaScript code
- • Inspect variables
Sources
- • Set breakpoints
- • Step through code
- • Watch variables
Network
- • Monitor HTTP requests
- • Check response times
- • Debug API calls
Elements
- • Inspect HTML structure
- • Edit CSS live
- • Debug layouts
Debugging Workflow
Identify
Reproduce the bug and identify error messages
Isolate
Narrow down to the specific code causing the issue
Debug
Use breakpoints and console to understand the flow
Fix & Test
Implement fix and verify it works in all scenarios
Debugging Best Practices
Use meaningful variable names
Add input validation
Use console.log strategically
Write unit tests
Debugging Methodology
Reproduce the bug consistently
Isolate the problem area
Use console and breakpoints
Test the fix thoroughly
Debugging — step by step
console Methods Beyond log
console.warn, console.error, and console.table give you richer output with colour coding and structured display. console.group and console.groupCollapsed let you nest related logs together, making long output scannable.
🎯 Quick Check
What is the purpose of a source map in JavaScript debugging?
JavaScript Fundamentals Complete!
Congratulations! You've mastered essential JavaScript concepts and debugging skills. Ready to build amazing applications!
Debugging JavaScript: summary
Key points
- Read the whole error:
TypeError: Cannot read properties of undefined (reading 'name')tells you exactly what wasundefined. - Breakpoints let you inspect the call stack and scope without adding logs.
- Conditional breakpoints (right-click a line number) pause only when an expression is true.
- The Network tab shows failed requests and API responses.
Frequently asked questions
›What does "Cannot read properties of undefined" mean?
You tried to access a property on something that's undefined, for example user.name when user hasn't loaded yet. Check where that value comes from, or use optional chaining (user?.name).