5 JavaScript Console Methods You're Not Using (But Should Be)
Everyone uses console.log(), but JavaScript's console object has powerful debugging methods that can save you hours. Here are 5 underused console methods that will make you a better debugger.
1. console.table() - View Arrays & Objects Beautifully
Instead of expanding objects in the console, display them as a table.
const users = [
{ name: 'Alice', age: 25, city: 'NYC' },
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'Tokyo' }
];
console.table(users);
// Displays a beautiful sortable table
Use case: When working with arrays of objects (API responses, user data).
2. console.group() - Organize Your Logs
Group related logs together to avoid console clutter.
console.group('User Login Process');
console.log('Step 1: Validating credentials...');
console.log('Step 2: Checking permissions...');
console.log('Step 3: Generating session token...');
console.groupEnd();
Use case: Tracking multi-step processes or function execution flow.
3. console.time() & console.timeEnd() - Performance Tracking
Measure how long your code takes to execute.
console.time('API Call');
// Simulate API call
await fetch('https://api.example.com/data');
console.timeEnd('API Call');
// Console: API Call: 245ms
Use case: Identifying slow functions or API calls.
4. console.assert() - Conditional Logging
Only log when a condition is false.
const user = { name: 'Alice', age: 25 };
console.assert(user.age >= 18, 'User must be 18 or older', user);
// Only logs if user.age < 18
Use case: Validating assumptions in your code during development.
5. console.trace() - See the Call Stack
Show where the current function was called from.
function calculateTotal(price, tax) {
console.trace('calculateTotal called');
return price + (price * tax);
}
calculateTotal(100, 0.1);
// Shows the entire call stack
Use case: Debugging complex applications with many function calls.
📋 Console Methods Cheatsheet
| Method | Purpose | When to Use |
|---|---|---|
console.table() |
Display data as table | Arrays of objects |
console.group() |
Group related logs | Multi-step processes |
console.time() |
Measure execution time | Performance debugging |
console.assert() |
Conditional logging | Validation checks |
console.trace() |
Show call stack | Complex debugging |
Your Challenge: Replace at least 3 console.log() calls in your current project with these more specific methods this week!
Comments
Post a Comment