DEV Community

Thomas Collardeau
Thomas Collardeau

Posted on

Two Simple Tips For Debugging In the Console

For my first post, I thought I would share 2 simple tips that I use when debugging Javascript in the console. You might very well know these already!

Reigning in the console

Not necessarily saying it's ideal, but if you're in the midst of an epic debugging sesh, you might end up in a situation with loads of console.log sprinkled all over your beautiful code like this:

// sometime later:
// in another file:
// more logs all over the place...

The flurry of logs in the console can quickly become a burden of confusion. What data belongs to what value, assuming we don't know what order they're even ran amidst the flow of our code?

Alt Text

One solution is that we can console.log('data: ', data), but we can also accomplish the same in fewer characters. What we can do instead is wrap our value in an object as such: console.log({ data }) and the console will print out the name of the variable before the data:

Alt Text

We're basically using ES6 shorthand syntax to log out an object that we create on the fly.

Refactoring Functions

Talk about ES6, another situation is that you might be writing your functions using more shorthand syntax like this:
const exclaim = txt => text + "!"
but then, some time later, you want to log txt, so you have to refactor the code to something like this:

const exclaim = txt => txt + "!"

// needs to become:

const exclaim = txt => {
  return text + "!"

Almost makes you want to skip the whole task. Well, you can also do the following and still log the parameter:

const exclaim = txt => console.log(txt) || txt + "!";

What happens here is that the console.log runs as normal and evaluates to false, so the parser evaluates the second expression of the OR clause txt + "!" and returns it as they are no more expressions to check. We sneaked in that log along the way and threw it away essentially. As such we can keep our functions as one-liners and still inspect them without jumping around in the editor.

Until Next Time!

Looking forward to being part of this community and learning along with everybody!

Top comments (2)

iamarek profile image
Arkadiusz Chatys

So simple and so clever!!! Love that.

collardeau profile image
Thomas Collardeau

I forgot to mention it for the first tip but you can also log multiple values at once with that trick, for instance:
console.log({user, followers})