As an experienced web developer, I bet you’ve been very familiar with console commands like
console.log()
console.info()
console.warn()
console.error()
But actually, browsers provide us more interesting and useful commands.
First, I’d like to introduce my favorite:
console.table()
Consider the simple array:
const users = [
{
name: "John",
age: 26,
sex: "M"
},
{
name: "Gordon",
age: 24,
sex: "M"
},
{
name: "Lisa",
age: 19,
sex: "F"
}
];
I know it could be printed with console.log()
, but you’ll find it more interesting with console.table()
Even, the table could be sorted by ascending/descending.
Next, it’s group()
Did you try to format your outputs so that you could easily recognize them?
const prefix = '\t';
for (let i = 0; i < 5; i++) {
console.log(`Testing ${i}`);
console.log(prefix, `how are you`);
console.log(prefix, `Bye!`);
}
Alternatively, you could use group()
instead.
for (let i = 0; i < 5; i++) {
console.group(`Testing ${i}`);
console.log(`how are you`);
console.log(`Bye!`);
console.groupEnd();
}
Also, console.groupCollapsed()
could collapse the message by default.
for (let i = 0; i < 5; i++) {
console.groupCollapsed(`Testing ${i}`);
console.log(`how are you`);
console.log(`Bye!`);
console.groupEnd();
}
Sometimes, we are keen to know the performance of a specific code block.
console.time()
and console.timeEnd()
could help us.
function foo() {
console.groupCollapsed(`Testing foo()`);
for (let i = 0; i < 1000; i++) {
console.log(i);
}
console.groupEnd();
}console.time(); // Start a timer
foo();
console.timeEnd();
Finally, I’d like to introduce another one debugger
, which just simply forces the browser paused like a breakpoint.
It’s hard to tell all the scenarios when you need it. But I bet you’ll find it very useful in many cases.