DEV Community

Alex Chen
Alex Chen

Posted on

JavaScript Console Tricks That Will Blow Your Mind

JavaScript Console Tricks That Will Blow Your Mind

The browser console is not just for console.log. Here are tricks most developers don't know.

1. console.table() — Beautiful Data Display

// ❌ Boring array logging
const users = [
  { id: 1, name: 'Alice', role: 'admin', active: true },
  { id: 2, name: 'Bob', role: 'user', active: false },
  { id: 3, name: 'Charlie', role: 'user', active: true },
];
console.log(users); // Hard to read

// ✅ Beautiful table!
console.table(users);
/*
┌─────┬─────────┬──────┬────────┐
│ (idx) │   name  │ role │ active │
├─────┼─────────┼──────┼────────┤
│   0 │  Alice  │admin │  true  │
│   1 │   Bob   │ user │ false  │
│   2 │ Charlie │ user │  true  │
└─────┴─────────┴──────┴────────┘
*/

// Show only specific columns
console.table(users, ['name', 'active']);
Enter fullscreen mode Exit fullscreen mode

2. console.time() — Performance Measurement

// Measure execution time
console.time('fetchData');

// ... some operation ...
await fetch('/api/users').then(r => r.json());

console.timeEnd('fetchData');
// Output: fetchData: 142.034ms

// Multiple timers
console.time('database');
console.time('api');
console.time('render');

// ... operations ...

console.timeEnd('render');    // render: 12ms
console.timeEnd('api');       // api: 89ms
console.timeEnd('database');  // database: 234ms
Enter fullscreen mode Exit fullscreen mode

3. CSS Styling in Console

// Add color and style to your logs
console.log(
  '%c ERROR! ',
  'background: red; color: white; font-weight: bold; padding: 4px 8px; border-radius: 4px;',
  'Something went wrong'
);

console.log(
  '%c SUCCESS! ',
  'background: green; color: white; font-weight: bold; padding: 4px 8px; border-radius: 4px;',
  'Operation completed'
);

// Warning style
console.warn('%c⚠️ Deprecated!', 'color: orange; font-weight: bold;');

// Info style
console.info('%cℹ️ Tip:', 'color: blue; font-weight: bold;', 'Use .map() instead of for loop');

// Large text
console.log('%cBIG', 'font-size: 40px; color: purple; font-weight: bold;');
Enter fullscreen mode Exit fullscreen mode

4. console.group() — Organized Logging

function processOrder(order) {
  console.group('📦 Processing Order');
  console.log('Order ID:', order.id);
  console.log('Items:', order.items.length);

  console.group('💳 Payment');
  console.log('Method:', order.payment.method);
  console.log('Amount:', order.payment.amount);
  console.groupEnd();

  console.group('🚚 Shipping');
  console.log('Address:', order.shipping.address);
  console.log('Speed:', order.shipping.speed);
  console.groupEnd();

  console.groupEnd(); // Closes "Processing Order"
}

processOrder(order);
/* Output:
📦 Processing Order
  Order ID: 12345
  Items: 3
  💳 Payment
    Method: credit_card
    Amount: $99.99
  🚚 Shipping
    Address: 123 Main St
    Speed: express
*/
Enter fullscreen mode Exit fullscreen mode

5. console.assert() — Conditional Logging

const value = getUserInput();
console.assert(value > 0, 'Value should be positive!', { actualValue: value });
// Only logs if assertion fails

function validateUser(user) {
  console.assert(user.email, 'Missing email!', user);
  console.assert(user.age >= 18, 'Underage user!', user);
  console.assert(user.role !== 'admin', 'Admin users should use admin panel!', user);
}
Enter fullscreen mode Exit fullscreen mode

6. console.count() & countReset()

// Track how many times something happens
function handleRequest(req) {
  console.count('Total requests');

  if (req.url.startsWith('/api')) {
    console.count('API requests');
  }

  if (req.statusCode === 404) {
    console.count('404 errors');
  }
}

// Output after handling 10 requests:
// Total requests: 10
// API requests: 7
// 404 errors: 2

// Reset counter
console.countReset('API requests');
Enter fullscreen mode Exit fullscreen mode

7. console.trace() — Call Stack

function funcA() { funcB(); }
function funcB() { funcC(); }
function funcC() { console.trace('Who called me?'); }

funcA();
/*
Output:
Trace: Who called me?
  at funcC (<anonymous>:3:17)
  at funcB (<anonymous>:2:5)
  at funcA (<anonymous>:1:5)
  at <anonymous>:1:1
*/
Enter fullscreen mode Exit fullscreen mode

8. console.dir() — Object Inspection

// See full object (not truncated like console.log)
const element = document.body;
console.log(element);   // Shows HTML representation
console.dir(element);   // Shows properties tree, expandable

// With depth option
console.dir(obj, { depth: null }); // Show all levels (no truncation)
console.dir(obj, { depth: 1 });   // Only one level deep
Enter fullscreen mode Exit fullscreen mode

9. $0-$4 — Last Selected Elements

// In Chrome/Firefox DevTools console:
// $0 = last selected element in Elements tab
// $1 = second-to-last selected element
// etc.

// Click on an element in DevTools → type in console:
$0.style.color = 'red';     // Change color of selected element
$0.getBoundingClientRect(); // Get position/size of selected element
$1.textContent             // Get text of previously selected element
Enter fullscreen mode Exit fullscreen mode

10. copy() — Copy to Clipboard

// Copy any value to clipboard (DevTools only!)
copy(JSON.stringify(data, null, 2));
// Now paste anywhere: Ctrl+V / Cmd+V

copy($0.outerHTML);        // Copy HTML of selected element
copy(document.cookie);      // Copy cookies
copy(localStorage);         // Copy all local storage
Enter fullscreen mode Exit fullscreen mode

11. queryObjects() — Find JS Objects

// Find all objects of a specific class (Chrome only!)
class User {}
const u1 = new User();
const u2 = new User();
queryObjects(User); // Returns [u1, u2]

// Useful for debugging memory leaks or finding instances
queryElements(React.Component); // All React components
Enter fullscreen mode Exit fullscreen mode

12. monitorEvents() — Debug Events

// Monitor all events on an element (Chrome only!)
monitorEvents(document.body, 'click');     // Log all clicks
monitorEvents(window, 'key');              // Log all key events
monitorEvents($0, 'mouse');               // Log mouse events on selected element

// Stop monitoring
unmonitorEvents(document.body);

// Monitor multiple event types
monitorEvents($0, ['click', 'touch', 'keydown']);
Enter fullscreen mode Exit fullscreen mode

13. getEventListeners() — View Event Listeners

// List all event listeners on an element (Chrome only!)
getEventListeners(document);
getEventListeners($0);  // On currently selected element

// Returns object with event types as keys:
// {
//   click: [{listener: fn, useCapture: false}, ...],
//   keydown: [{listener: fn, useCapture: true}]
// }
Enter fullscreen mode Exit fullscreen mode

14. _ (underscore) — Last Result

// In Chrome console, _ holds the last evaluated expression
'hello'.toUpperCase()
// "HELLO"
_.length
// 5

[1, 2, 3].map(x => x * 2)
// [2, 4, 6]
_.reduce((a, b) => a + b, 0)
// 12

// Useful for chaining operations without variables
Enter fullscreen mode Exit fullscreen mode

15. clear() — Clean Slate

clear(); // Clear console (same as clicking 🚫 button)

// Keyboard shortcut: Ctrl+L (Cmd+L on Mac)
Enter fullscreen mode Exit fullscreen mode

Quick Reference Card

Method Purpose Use When
console.log() Basic output Always
console.error() Error output Errors
console.warn() Warnings Deprecations
console.table() Tabular data Arrays/objects
console.time/timeEnd() Timing Performance
console.group/groupEnd() Grouping Complex logging
console.assert() Conditionals Debugging assumptions
console.count/countReset() Counting Event tracking
console.trace() Stack trace Debugging calls
console.dir() Object inspection DOM/deep objects
%c styling Color/style Important messages

Which console trick is your favorite? Any I missed?

Follow @armorbreak for more JavaScript content.

Top comments (0)