Back to KB
Difficulty
Intermediate
Read Time
4 min

How to Debug JavaScript Like a Pro

By Codcompass TeamΒ·Β·4 min read

Stop using console.log for everything. Here's a better way.

Level 1: console.log Done Right

// ❌ Bad: No context
console.log(data);
console.log(user);
console.log(error);

// βœ… Good: Labeled and structured
console.log('User data:', { id: user.id, name: user.name, role: user.role });
console.log('API response status:', res.status);

// βœ… Better: Console styling
console.log('πŸš€ App started');
console.log('⚠️ Warning: Rate limit approaching', { remaining: limit });
console.error('❌ Fetch failed:', error.message);

// βœ… Best: Table format for arrays/objects
const users = [{name:'Alex',age:30}, {name:'Sam',age:25}];
console.table(users);
// β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
// β”‚ (index) β”‚ name β”‚ age β”‚
// β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€
// β”‚    0    β”‚ Alex β”‚ 30  β”‚
// β”‚    1    β”‚ Sam  β”‚ 25  β”‚
// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Enter fullscreen mode Exit fullscreen mode

Level 2: Console Methods You Didn't Know About

// Group related logs
console.group('API Request');
console.log('URL:', url);
console.log('Method:', method);
console.log('Headers:', headers);
console.groupEnd();

// Assert (only logs if condition is false)
console.assert(user.age >= 18, 'User is underage:', user.age);
// Assertion failed: User is underage: 15

// Time operations
console.time('fetchData');
await fetchData();
console.timeEnd('fetchData'); // fetchData: 1.234s

// Count how many times something happens
function handleRequest(req) {
  console.count('requests'); // requests: 1, 2, 3...
}

// Trace the call stack
function process(data) {
  console.trace('process called');
  // Shows full stack trace of who called this function
}

// Dir: Inspect DOM elements or objects
cons

πŸŽ‰ Mid-Year Sale β€” Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register β€” Start Free Trial

7-day free trial Β· Cancel anytime Β· 30-day money-back