DEV Community

Alex Chen
Alex Chen

Posted on

How to Debug JavaScript Like a Pro

How to Debug JavaScript Like a Pro

Stop using console.log for everything. Here's how the pros debug.

1. Chrome DevTools Basics You Might Not Know

// Break on DOM changes (magic!)
// Elements panel → Right-click element → Break on → 
//   subtree modifications / attribute modifications / node removal

// Console as calculator
> 2 + 3 * 4          // 14
> $$('.item').length  // $$ = querySelectorAll, $ = querySelector
> $_                  // Last result
> $_.length           // Length of last result

// Copy to clipboard from console
copy(JSON.stringify(data, null, 2));

// Clear console (without clicking)
clear();
Enter fullscreen mode Exit fullscreen mode

2. Debugger Statement — Better Than console.log

function processUser(user) {
  debugger; // Pauses execution here — like a breakpoint!

  const normalized = user.name.trim().toLowerCase();
  const email = user.email.toLowerCase();

  return { name: normalized, email };
}
Enter fullscreen mode Exit fullscreen mode

When execution hits debugger, DevTools opens automatically and you can:

  • Inspect all variables in current scope
  • Step through code line by line
  • Watch expressions change in real time
  • Call functions manually in the console

3. Conditional Breakpoints

// Don't just set a regular breakpoint → Right-click → "Edit breakpoint"
// Enter a condition:

i > 1000              // Only break after loop iteration 1000
user.id === 'abc123' // Only break for specific user
data.length === 0     // Only break when array is empty
typeof x === 'undefined'  // Only break when undefined
Enter fullscreen mode Exit fullscreen mode

This is game-changing for debugging loops or frequently-called functions!

4. Logpoint — No More Adding/Removing console.log

// Right-click line number → "Add logpoint"
// Enter: "User ID: " + userId
// Output appears in console WITHOUT pausing execution!
// No need to modify source code or remove logs later!
Enter fullscreen mode Exit fullscreen mode

5. Network Tab Tricks

// Copy as fetch (right-click any network request)
// Generates:
fetch('/api/users', {
  "headers": {
    "accept": "application/json",
    "authorization": "Bearer xxx"
  },
  "method": "GET"
});

// Block requests (Network tab → Right-click → Block request URL pattern)
// Block third-party analytics while debugging!

// Throttle network (Network tab → No throttling dropdown)
// Simulate Slow 3G, Fast 3G, or custom speeds
// Test loading states and error handling!
Enter fullscreen mode Exit fullscreen mode

6. Performance Profiling

// Performance tab → Record → Do action → Stop recording
// See exactly where time is spent:
// - Loading (network)
// - Scripting (JS execution)
// - Rendering (paint/layout)
// - Painting (pixel drawing)

// Identify long tasks (>50ms blocks main thread!)
// These cause jank and slow UI
Enter fullscreen mode Exit fullscreen mode

7. Memory Debugging

// Memory tab → Take heap snapshot
// Compare snapshots to find memory leaks

// Common leak patterns:
// 1. Forgotten timers: setInterval without cleanup
// 2. Event listeners never removed
// 3. Closures holding references
// 4. Detached DOM nodes

// Allocation sampling → Find what's allocating memory over time
// Allocation instrumentation on timeline → Exact allocation stack traces
Enter fullscreen mode Exit fullscreen mode

8. Source Maps

// Your built code is minified but source maps let you debug original:
// devtool://source-map-url

// Verify source maps are working:
// Sources panel → Check that original files appear
// Set breakpoints in YOUR code, not the minified bundle!
Enter fullscreen mode Exit fullscreen mode

9. The Console API Beyond log()

// Already know console.log? Try these:

console.warn('Deprecation warning');     // Yellow warning style
console.error('Something broke');        // Red error style + stack trace
console.info('Informational');           // Blue info style
console.debug('Debug detail');           // Only shows if verbose logging enabled
console.table(users);                    // Beautiful table format
console.group('Section'); ... console.groupEnd(); // Group related logs
console.time('label'); ... console.timeEnd('label'); // Timing
console.assert(condition, 'message');    // Conditional failure
console.trace('Here');                   // Stack trace at this point
console.count('label');                  // Count occurrences
console.dir(obj, { depth: null });       // Deep object inspection
console.memory;                          // Heap usage stats
Enter fullscreen mode Exit fullscreen mode

10. Node.js Debugging

# Run with inspector
node --inspect server.js
# Then open chrome://inspect in Chrome

# Or use built-in debugger
node inspect server.js
# Commands: cont, next, step, out, repl, watchers

# VS Code: Just press F5 (auto-attaches debugger!)
# Add launch config in .vscode/launch.json
Enter fullscreen mode Exit fullscreen mode

11. React DevTools

// Components tab: See props, state, hooks, context
// Click component → see why it re-rendered (⚡ icon)
// Profile tab: Record, interact, see which components rendered and why

// Key features:
// - Search for components by name
// - Highlight updates in page (visualize re-renders)
// - Edit props/state live (experimentation)
// - View hooks and their values
Enter fullscreen mode Exit fullscreen mode

12. Error Tracking Integration

// For production bugs you can't reproduce locally:

// Sentry (most popular)
import * as Sentry from '@sentry/browser';
Sentry.init({ dsn: 'YOUR_DSN' });

try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
  // Gets: stack trace, user info, browser, OS, release, tags
}

// LogRocket (session replay)
// Records video of what user did before error occurred!
Enter fullscreen mode Exit fullscreen mode

What's your favorite debugging trick?

Follow @armorbreak for more developer content.

Top comments (0)