DEV Community

Josh Ellis
Josh Ellis

Posted on

Beyond Basic Console.log()

Here are a few quick tips that you can add to your debugging toolkit.

Using Objects

Instead of logging naked variables, consider using objects to quickly create labeled logs:

const hello = 'hello'
const num = Math.random()
console.log({ hello, num })
=> { hello: "hello", num: 0.9891318026649385 }
Enter fullscreen mode Exit fullscreen mode

Warn & Error

Most of you probably know this one, but it's very useful because it gives you a stack trace (meaning you can easily find where the warning/error is coming from). Therefore, I'm including it for the few who haven't heard of it.

You can use either with a string like console.warn('warning') or console.error('error')

Or you can pass an error: console.error(new Error('message'))

I use this a lot when I'm temporarily logging multiple things, but want one of them to stand out in the console.

Group

I haven't yet found a reason to use this one, but I can see how it could be useful. From MDN docs:

console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
Enter fullscreen mode Exit fullscreen mode

In the console, you get collapsible groups.

Maybe someone can share how they're using this in the comments?

Tables

If you're working with an array or object, sometimes it's useful to visualize it in a table. From MDN docs:

var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
console.table(people);
Enter fullscreen mode Exit fullscreen mode

This will display a table using the index numbers for row and column headers. You can also use console.table() on objects, and it will use the keys as the row headers.

Conclusion

Were any of these new to you? What did I miss? I'd love to hear your tips about using the console for web dev!

Top comments (3)

Collapse
 
madhusudanbabar profile image
Krypton | Madhusudan Babar

Hey,
Thanks for the article, actually i was unaware of that console.group.

Collapse
 
hb profile image
Henry Boisdequin

Thanks for the debugging tips!

Collapse
 
promikecoder2020 profile image
ProMikeCoder2020

I have seen more than enough articles on this subject