🐛

How to Debug JavaScript Code

JavaScriptBeginner

Tools and techniques for debugging.

Code Example

JavaScript
// 1. console methods
console.log('Basic log');
console.info('Info message');
console.warn('Warning');
console.error('Error');

// Table view
const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];
console.table(users);

// Group logs
console.group('User Data');
console.log('Name: Alice');
console.log('Age: 30');
console.groupEnd();

// Collapsed group
console.groupCollapsed('Hidden Group');
console.log('This is hidden by default');
console.groupEnd();

// Timer
console.time('operation');
// Expensive operation
for (let i = 0; i < 1000000; i++) {}
console.timeEnd('operation');

// Count
for (let i = 0; i < 5; i++) {
  console.count('loop');
}

// Assert
const value = 10;
console.assert(value > 5, 'Value should be greater than 5');
console.assert(value > 20, 'This will show error');

// 2. Debugger statement
function problematic() {
  const x = 10;
  debugger; // Pauses execution here
  const y = x * 2;
  return y;
}

// 3. Try-catch with detailed error
try {
  JSON.parse('invalid json');
} catch (error) {
  console.error('Error:', error.message);
  console.error('Stack:', error.stack);
  console.error('Name:', error.name);
}

// 4. Custom error logging
function logError(error, context) {
  console.error({
    message: error.message,
    stack: error.stack,
    context,
    timestamp: new Date().toISOString()
  });
}

// 5. Trace function calls
function a() {
  console.trace('Called from a');
  b();
}

function b() {
  console.trace('Called from b');
  c();
}

function c() {
  console.log('In c');
}

a(); // Shows call stack

// 6. Conditional breakpoints (in DevTools)
// Right-click line number in Sources tab
// Add condition: x > 10

// 7. Performance profiling
console.profile('MyProfile');
// Code to profile
console.profileEnd('MyProfile');

// 8. Memory inspection
function createClosure() {
  const largeArray = new Array(1000000).fill('data');
  return () => largeArray;
}

const closure = createClosure();
// Check Memory tab in DevTools

// 9. Network debugging
// Network tab: filter by type, size, time
// Copy as cURL for reproduction

// 10. Source maps
// Enable in DevTools settings
// Maps minified code to original source

// 11. Break on exceptions
// DevTools > Sources > Pause on exceptions
// All exceptions or uncaught only

// 12. Watch expressions
// Add variables to watch in Scope panel
// Monitor value changes during debugging

Explanation

Use console methods for structured logging. debugger statement pauses execution. Try-catch for error handling. DevTools: breakpoints, watch expressions, network tab, memory profiling.

Related Tutorials