Console Logging the Right Way

Amit Merchant · March 22, 2022 ·

Haters gonna hate and call you uncultured but when it comes to debugging, doing console.log() is one of best the best ways of all time. Period. Well! sort of!

Console logging is great but I was always facing this one issue while doing it. So, I’m going to explain in this and the solution to it (that I use) in this article.

The usual way

So, when working with JavaScript, you might be doing console.log() to log something to the browser console. So, let’s say if I want to log the following object to the console, here’s how I can do it.

const User = {
    id: 1, 
    name: 'Jon Doe'
};

console.log(User);
// { id: 1, name: 'Jon Doe' }

Here’s how it would look like in the browser’s console.

This will log the User object to the console but if you can tell, the problem with this approach is, you don’t exactly know which variable has been logged.

In a real-world scenario where you are logging multiple variables from your codebase, it kind of gets confusing what all variable has been logged to the console and you may tend to lose the context entirely.

To mitigate this here’s what I do instead.

Logging the variable as an object

To see which variable has been logged to the console, all you can do is log that variable as an object like so.

const User = {
    id: 1, 
    name: 'Jon Doe'
};

console.log({User});
// { User: { id: 1, name: 'Jon Doe' } }

Here’s how this would look like in the browser’s console.

As you can tell, by logging the variable using this method, the browser’s console will also show the name of the variable while doing so!

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?