Here are some cool “secrets” and lesser-known tips about console.log
in JavaScript:
1. Custom Styling
You can style your console logs using %c
. Add custom CSS to make your logs stand out!
console.log('%cHello, world!', 'color: blue; font-size: 20px; background: yellow; padding: 5px; border-radius: 5px;');
2. String Substitutions
console.log
supports placeholders for string substitutions, like %s
, %d
, and %o
.
console.log('My favorite number is %d and my name is %s!', 42, 'Alice');
3. Logging Objects Dynamically
When you log an object, its current state is shown live, not the snapshot at the time of logging. This means the object in the console updates as its properties change.
const obj = { a: 1 };
console.log(obj);
obj.a = 2; // You'll see this change in the console!
4. Grouping Logs
You can group multiple logs together in collapsible groups for better organization.
console.group('Outer Group');
console.log('Hello from outer group');
console.group('Inner Group');
console.log('Hello from inner group');
console.groupEnd();
console.groupEnd();
5. Timers
Use console.time
and console.timeEnd
to measure how long a piece of code takes.
console.time('Loop Timer');
for (let i = 0; i < 1000000; i++) {}
console.timeEnd('Loop Timer');
6. Clear the Console
Quickly clear the console with console.clear()
.
console.log('Something cool');
console.clear(); // Wipes the console
7. Counting
console.count
counts how many times it’s called.
console.count('Count this!');
console.count('Count this!');
console.count('Another count');
8. Stack Traces
console.trace
shows the stack trace of where the log is called.
function a() {
function b() {
console.trace('Trace example');
}
b();
}
a();
9. Conditional Debugging with Breakpoints
You can set breakpoints directly in console.log
by typing debugger;
in your code. When the debugger runs, you can inspect everything at that point.
console.log('Debugging here');
debugger;
console.log('You passed the debugger!');
10. Using console.table
Display arrays or objects as a table for better readability.
const fruits = [
{ name: 'Apple', color: 'Red' },
{ name: 'Banana', color: 'Yellow' },
];
console.table(fruits);
Bonus: Easter Egg
In some browsers like Chrome, type this in the DevTools console:
console.log('%cSTOP!', 'color: red; font-size: 50px; font-weight: bold;');
A playful way to grab attention! 🚀