Beyond Console.log
Chrome DevTools is a powerful suite of web development tools built directly into the Chrome browser. While most developers use basic features, mastering advanced techniques can dramatically improve your debugging productivity.
// Instead of this:
console.log(data);
console.log('User:', user);
console.log('Error:', error);
// Use these advanced techniques:
console.table(users);
console.group('Authentication Flow');
console.trace('Function call stack');
console.time('API Request');Advanced Console Techniques
Structured Logging
// Console tables for array data
const users = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bob', age: 35 },
];
console.table(users);
// Console groups for hierarchical data
console.group('User Profile');
console.log('Name:', user.name);
console.log('Email:', user.email);
console.group('Permissions');
console.log('Read:', user.canRead);
console.log('Write:', user.canWrite);
console.groupEnd();
console.groupEnd();
// Console counting
function processData(items) {
items.forEach(item => {
console.count('Items processed');
// Processing logic
});
}Performance Measurement
// Measure execution time
console.time('Data Processing');
const processed = rawData.map(item => ({
...item,
processed: true,
}));
console.timeEnd('Data Processing');
// Profile memory usage
console.memory;
// Record performance timeline
console.profile('Function Execution');
expensiveFunction();
console.profileEnd('Function Execution');
// Assert conditions
function validateUser(user) {
console.assert(user.age >= 18, 'User must be 18 or older', user);
return user.age >= 18;
}Advanced Formatting
// CSS styling
console.log(
'%c Error!',
'color: red; font-size: 20px; font-weight: bold;'
);
console.log(
'%c Success!',
'background: green; color: white; padding: 5px; border-radius: 3px;'
);
// String substitution
const user = { name: 'John', age: 30 };
console.log('User: %o, Age: %d', user, user.age);
// Object inspection
console.dir(document.body, { depth: null, colors: true });Sources Panel Mastery
Workspace Integration
// 1. Open DevTools → Sources
// 2. Right-click in panel → Add folder to workspace
// 3. Select your project directory
// 4. Authorize filesystem access
// 5. Edit files directly in DevTools
// 6. Changes save to filesystem automatically
// Benefits:
// - Edit files without leaving browser
// - See changes immediately
// - Preserves formatting
// - Works with any projectSource Maps
// webpack.config.js
module.exports = {
devtool: 'source-map',
module: {
rules: [
{
test: /.js$/,
use: 'source-map-loader',
enforce: 'pre',
},
],
},
};
// In DevTools:
// Enable JavaScript source maps
// Enable CSS source maps
// Settings → Preferences → Enable source mapsCode Snippets
// Create reusable code snippets
// Sources → Snippets → New snippet
// Example: Performance monitor
(function() {
const fps = document.createElement('div');
fps.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
background: rgba(0,0,0,0.7);
color: #0f0;
padding: 10px;
font-family: monospace;
z-index: 9999;
`;
document.body.appendChild(fps);
let frames = 0;
let lastTime = performance.now();
function update() {
frames++;
const now = performance.now();
if (now >= lastTime + 1000) {
fps.textContent = `FPS: ${frames}`;
frames = 0;
lastTime = now;
}
requestAnimationFrame(update);
}
update();
})();Network Panel Deep Dive
Advanced Filtering
``javascript // Filter by URL pattern url:*.json
// Filter by response code status:200
// Filter by response size -larger-than:1000
// Filter by response time >:500
// Multiple filters domain:example.com status:200 mime-type:json
### Network Throttling
// Simulate different network conditions // Network tab → Throttling dropdown
// Presets: // - Offline // - Slow 3G (500ms RTT, 50 Kbps) // - Fast 3G (100ms RTT, 1 Mbps) // - Custom (configure your own)
// Use for testing: // - Progressive loading // - Error handling // - Loading states // - Performance optimization
### HAR File Analysis
// Export HAR (HTTP Archive) file // Network tab → Right-click → Save all as HAR with content
// Analyze HAR file const har = await fetch('./network.har').then(r => r.json());
// Find slowest requests const slowRequests = har.log.entries .filter(entry => entry.time > 1000) .sort((a, b) => b.time - a.time);
console.table(slowRequests.map(entry => ({ url: entry.request.url, time: entry.time + 'ms', size: entry.response.bodySize + ' bytes', })));
// Find largest responses const largeResponses = har.log.entries .filter(entry => entry.response.bodySize > 100000) .sort((a, b) => b.response.bodySize - a.response.bodySize);
## Performance Panel Secrets
### Performance Profiling
// Record performance profile // Performance → Record → Perform action → Stop
// Analyze: // 1. Flame chart shows call hierarchy // 2. Bottom-up shows time per function // 3. Call tree shows execution path
// Optimize based on findings: // - Identify long-running functions // - Find frequent garbage collections // - Detect layout thrashing // - Spot memory leaks
### Memory Profiling
// Take heap snapshot // Memory → Heap snapshot → Take snapshot
// Find detached DOM nodes // 1. Take snapshot // 2. Interact with app // 3. Take another snapshot // 4. Compare snapshots // 5. Look for "Detached DOM tree"
// Find memory leaks // 1. Take snapshot (baseline) // 2. Perform actions // 3. Force garbage collection // 4. Take snapshot // 5. Compare for memory increase
// Allocation sampling // Memory → Allocation sampling → Start // Perform actions // Stop and analyze allocation sites
### Runtime Performance
// Measure rendering performance const measureFPS = () => { let frames = 0; let lastTime = performance.now();
function measure() { frames++; const now = performance.now();
if (now >= lastTime + 1000) { console.log(FPS: ${frames}); frames = 0; lastTime = now; }
requestAnimationFrame(measure); }
measure(); };
measureFPS();
// Identify rendering bottlenecks // Performance → Enable frames // Look for long frames (>16ms) // Investigate causes in flame chart
## Debugging Techniques
### Conditional Breakpoints
// Right-click line number → Add conditional breakpoint // Enter condition: user.id === 123
// Only breaks when condition is true // Useful for debugging specific states
// Examples: user.age < 18 data.length === 0 response.status !== 200
### Logpoints
// Right-click line number → Add logpoint // Enter: User: ${user.name}, Age: ${user.age}
// Prints message without stopping execution // Great for production debugging // No code changes needed
### Exception Handling
// Enable pause on exceptions // Sources → Pause on exceptions icon // Check both checkboxes: // - Pause on uncaught exceptions // - Pause on caught exceptions
// Debug async code // Enable async stack traces // Settings → Preferences → Enable async stack traces
// Debug promises Promise.resolve() .then(() => { debugger; // Breaks here return fetchData(); }) .then(data => { console.log(data); });
### Blackboxing Scripts
// Ignore third-party code while debugging // Settings → Blackboxing → Add pattern
// Patterns to blacklist: react-dom.production.min.js react.production.min.js bundle.min.js
// Benefits: // - Cleaner call stacks // - Focus on your code // - Faster debugging
## Application Panel
### Service Worker Debugging
// Application → Service Workers // View registered service workers // Inspect service worker code // Force update service worker // Unregister service workers
// Debug service worker // Click on service worker link // Opens dedicated DevTools for SW // Set breakpoints in SW code
### Cache Storage
// Application → Cache Storage // View cached responses // Inspect cache contents // Clear specific caches // Test cache strategies
// Test offline functionality // Network → Offline checkbox // Service Worker checkbox // Verify cached resources load
### Local Storage Inspection
// Application → Local Storage // View all localStorage data // Edit values inline // Add new items // Delete items // Clear all storage
// Use console to manipulate localStorage.setItem('user', JSON.stringify(user)); const user = JSON.parse(localStorage.getItem('user'));
## Command Menu
### Quick Actions
``javascript
// Open Command Menu
// Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows)
// Useful commands:
- "Show nodes"
- "Capture node screenshot"
- "Block request domain"
- "Throttling"
- "Clear site data"
- "Enable query fragments"
- "Show console"
// Navigate quickly
Cmd+P (Mac) or Ctrl+P (Windows)
Start typing file name
Jump to any fileLighthouse Integration
Performance Audits
// Run Lighthouse audit
// Lighthouse → Generate report
// Categories:
- Performance
- Accessibility
- Best Practices
- SEO
- Progressive Web App
// Key metrics:
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Time to Interactive (TTI)
// Target scores:
- Performance: 90+
- Accessibility: 100
- Best Practices: 90+
- SEO: 90+Advanced Workflows
Remote Debugging
// Debug mobile devices
// 1. Enable USB debugging on device
// 2. Connect device via USB
// 3. chrome://inspect on desktop
// 4. Configure port forwarding
// 5. Open DevTools for device
// Debug Chrome on Android
// Enable USB debugging
// Connect device
// chrome://inspect → Inspect
// Debug Safari on iOS
// Enable Web Inspector on iOS
// Connect device
// Safari → Develop → [Device]Override Files
// Override network responses
// Sources → Overrides → Select folder
// Network tab → Right-click response → Override content
// Use cases:
// - Test bug fixes without deploying
// - Modify CSS without build
// - Change JavaScript logic
// - Mock API responses
// Works with:
// - JavaScript
// - CSS
// - HTML
// - ImagesKeyboard Shortcuts
Essential Shortcuts
``javascript // General Cmd+Option+I - Open DevTools Cmd+Shift+C - Select element Cmd+Shift+D - Toggle device mode Cmd+Shift+M - Toggle device mode
// Console Cmd+Option+J - Show console Cmd+Enter - Execute code Shift+Enter - Multi-line input
// Elements Cmd+Z - Undo Cmd+Shift+Z - Redo H - Hide element Delete - Delete node
// Sources Cmd+P - Open file Cmd+G - Find next Cmd+Shift+G - Find previous Cmd+B - Toggle breakpoint
## Tips and Tricks
### Quick Element Selection
// Inspect element quickly // Cmd+Shift+C then click element
// Select element via console $('button') // First button $$('a') // All links $x('//div') // XPath selector
// Copy element copy($0) // Copies last selected element
### Debugging State
// Monitor function calls monitor(functionName);
// Get event listeners getEventListeners(document.querySelector('button'));
// Inspect DOM node dir(document.body);
// Query selector document.querySelectorAll('div').forEach(div => { console.log(div); });
## Conclusion
Master Chrome DevTools to debug faster and more effectively. These advanced techniques will transform your debugging workflow from frustrating to efficient.
Key takeaways:
- Use structured logging instead of console.log
- Leverage workspace integration for faster edits
- Profile performance to identify bottlenecks
- Use conditional breakpoints for targeted debugging
- Master keyboard shortcuts for speed
Debug like a pro with Chrome DevTools!