Finding and Fixing Bugs
Debugging is the process of finding and fixing errors (bugs) in your code. Every developer spends significant time debugging.
Modern browsers provide powerful developer tools including console logging, breakpoints, step-through debugging, and performance profiling.
Learning effective debugging techniques is essential for becoming a productive developer and solving problems efficiently.
// Console methods for debugging
console.log('Basic log message');
console.info('Informational message');
console.warn('Warning message');
console.error('Error message');
// Log multiple values
const user = { name: 'Alice', age: 30 };
console.log('User:', user);
// console.table for arrays and objects
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
];
console.table(users);
// console.time for performance measurement
console.time('operation');
// ... some code ...
console.timeEnd('operation'); // Logs: "operation: 1.23ms"
// console.assert for testing conditions
const age = 15;
console.assert(age >= 18, 'User must be 18 or older!');
// console.group for organizing logs
console.group('User Details');
console.log('Name:', user.name);
console.log('Age:', user.age);
console.groupEnd();
// Debugger statement (pauses execution in dev tools)
function complexFunction(data) {
debugger; // Execution will pause here if dev tools open
const result = processData(data);
return result;
}
// Stack trace
console.trace('Show call stack');
- console.log() - Most basic debugging tool, print values
- console.table() - Display arrays/objects as tables
- console.time/timeEnd() - Measure code execution time
- console.assert() - Log error if condition is false
- debugger statement - Pause execution in browser dev tools
- Breakpoints - Set in browser to pause at specific lines
- Step through - Execute code line by line in debugger
- Watch expressions - Monitor variable values in real-time
Try Debugging Techniques
<div class="debug-demo">
<h3>Debugging Examples</h3>
<p><em>Open your browser's Developer Tools (F12) to see console output!</em></p>
<div class="example">
<h4>1. Console Methods</h4>
<button id="consoleBtn">Run Console Examples</button>
<div id="consoleInfo">Check the browser console (F12) for output</div>
</div>
<div class="example">
<h4>2. Performance Timing</h4>
<button id="timingBtn">Measure Performance</button>
<div id="timingOutput"></div>
</div>
<div class="example">
<h4>3. Bug Hunter</h4>
<p>This code has a bug! Click to run and check the console for errors.</p>
<button id="buggyBtn">Run Buggy Code</button>
<button id="fixedBtn">Run Fixed Code</button>
<div id="bugOutput"></div>
</div>
</div>
Note: Use DevTools: Learn your browser's Developer Tools (F12) - they're your most powerful debugging weapon.
Note: console.log Strategically: Place logs before/after problem areas to narrow down where errors occur.
Note: Remove Debug Code: Don't ship console.log statements to production - remove or use proper logging libraries.