loading...

Stop using default console.log, check this instead

guilhermetoti profile image Guilherme Toti Updated on ・4 min read

So, you are always using console.log to debug your application, right?
In this post, I will show you alternatives to better debugging.

Interpolating

How are you interpolating your console.log with variables? Are you doing something like this?

const a = 'World';
console.log('Hello ' + a);

That is not wrong, but there are better ways to do that.

The % Operator

The first way is using the % operator.
I believe it works almost like any other programming language that allows you to do that.

So, you can use it like this:

console.log('Hello %s', a);

There are other options, too, like %i for integers or %f for float numbers.
Google that, and you will see a lot of other options ;)

Template String

Template String is called when you wrap a string with backticks, e.g.:

const a = `This is a template string`;

But that is unnecessary if you are not interpolating variables on it, it is preferable to use single/double quotes in this case.

To use template string, you must wrap your variables in ${}, let's see how your console.log would look like:

const a = 'World';
console.log(`Hello ${a}`);

Looks clean, right?!

Styled

Did you know you can apply style to a console.log?

To do that, you need to start your console.log string with %c, and the second argument should be the "inline" CSS. Check this out:

console.log('%c I am a great text!', 'font-size: 26px; color: blue;');

Copy and paste that in your console and check what you get.
That's awesome, huh?

Warning

When you need to add a warning, you can do it using console.warn.

To do that, use:

console.warn('This is some warning');

Error

Yeah, I know, it's sux to have some error in our application.
But when we are trying to debug the errors to fix them, why not display an error instead of a default log?

To do that, use:

console.error('This is some error');

Info

Sometimes you just want to show some information differently.
Using console.info, it will display a little "info icon" before your log.

To do that, use:

console.info('Just a simple information');

Assert

You can use assert to test something.
In the first argument, you pass what you want to test, and the second argument is what to show in case the assert fails.
If the assert returns true, it won't display anything.

console.assert(1 !== 1, '1 is equal to 1');

Viewing DOM Elements

Let's say you have something like:

const p = document.querySelector('p');

So, you have the variable p as the first <p> of your page.
If you console.log it, you will probably get just the DOM element, but you can't know it's properties, et cetera.

BUT, we have the brave console.dir to save us!

console.dir(p);

It will log the DOM element as an object so that you can check all its properties, events, et cetera! AWESOME! \o/

Grouping

Sometimes you are logging things inside an array, and it becomes spamming in your console, right?

Take this as an example:

const dogs = [
  { name: 'Ricota', age: 2 },
  { name: 'Gorgonzola', age: 8 }
];

dogs.forEach(dog => {
  console.log(`Dog: ${dog.name}`);
  console.log(`Dog: ${dog.name} is ${dog.age} years old`);
  console.log(`Dog: ${dog.name} is ${dog.age * 7} years old for real`);
})

Yep, I know, it's not that easy to read your console this way.
BUT we can group them!

We have two options.

console.group()

console.group will group it and shows it initially open (but you can close them)

Let's see an example:

dogs.forEach(dog => {
  console.group(dog.name); // This is the group title
  console.log(`Dog: ${dog.name}`);
  console.log(`Dog: ${dog.name} is ${dog.age} years old`);
  console.log(`Dog: ${dog.name} is ${dog.age * 7} years old for real`);
  console.groupEnd(dog.name); // To end the group, you MUST pass the same as you are using in your group title
});

console.groupCollapsed()

console.groupCollapsed will group it too, but initially shows it closed, so you can open what you want only.

Let's see an example:

dogs.forEach(dog => {
  console.groupCollapsed(dog.name); // This is the group title
  console.log(`Dog: ${dog.name}`);
  console.log(`Dog: ${dog.name} is ${dog.age} years old`);
  console.log(`Dog: ${dog.name} is ${dog.age * 7} years old for real`);
  console.groupEnd(dog.name); // To end the group, you MUST pass the same as you are using in your group title
});
  • For both, you need to close it with console.groupEnd().
  • For both, you need the same title when creating the group and when ending the group.

Table

You can generate a table in your console, oh yes, you really can!

Using the same dogs data example, try this in your console:

const dogs = [
  { name: 'Ricota', age: 2 },
  { name: 'Gorgonzola', age: 8 }
];
console.table(dogs);

It will show you a table with index, name, and age headers.

Clear

Now you did a lot of stuff in your console, why don't you clear it before continue testing another stuff?

Yes, you can clear it by using:

console.clear();

And right now you have a new and fresh console right up to you!

That's all folks!
I hope you guys enjoy it, and keep learning!

Posted on by:

guilhermetoti profile

Guilherme Toti

@guilhermetoti

A friendly guy who loves coding and photography.

Discussion

markdown guide
 

Thanks man!
The % operator is like a placeholder.
Let’s say you have:

console.log(“my %s”, “string”)
> “my string”

In this case, the second argument (“string”) will be replaced at %s.

There is also a %f for float numbers, and it’s cool because you can do something like:

console.log(“my %.2f”, 12.3456789)
> 12.34
 

Great, thank you for this!

In your first example I think it is supposed to read
console.log('Hello ' + a);

 

Thank you!
Yes! You're right! That was my mistake! Just fixed it, thanks!!!

 

In the first example, my preferred method is normally the template string. I have trouble seeing the advantage of the % operator compared to concatenating the variables. Other than that, this article was useful and discovered me the dir and group methods!

 

Yeah, I do not see a lot of advantages using % operator either, but I bring it just as informative content, it's a "good to know" thing...
Thanks! yesss, dir an group can be very helpful!

 

The % syntax is for seasoned programmers who started with C and are now bald and wrinkly. printf still ringing a bell? 👩🏼‍🦲

 

I few ones I didn't know like console.dir. Thanks for this!

 
 

Thanks for the article, console.trace() can be usefull sometimes.

 

Thanks!
True! I completely forgot about console.trace(), thanks for remind me!

 

Trace will show the stack trace, where that fails.
Let’s say in your app you have like a function that calls another function, that calls another function.
If you add a trace in the last function and something happen, it will log exactly where happened, like:

function_3 at line 1 (example)
function_2 at line 5 (example)
function_1 at line 88 (example)
 

Oo! I like that one a lot. :)

 

Mind blowing. Thank you for this article. Pity I always did console.log to dissect my objects and arrays. I think i going to overuse console.table now. :)

 

You’re welcome!
It is really mind blowing! I have been using .log for years! Now I can debug stuff way faster!

 

First example can also be written as console.log('Hello', a)

 

Sorry for the dumb question but do you need a certain console for this to work? I tried both the CSS and grouping things after updating to the latest version of node and neither works. What am I missing? I'm on a Mac using the Terminal app.

 

Oh, I’m not sure how it works on node, if node has some limitations, but, my examples were all done by any web browser console (developer tools)

 

Oooooooooh! Haha. I totally assumed the node terminal. That makes a LOT more sense now. Thanks for the fast reply.

 

But can you tell how to do this using ... Assignment and an array of values? :) nice write up. Thank you.

 

You can do it the same way! You can use ... assignment and array of values in a console.log!

Just like:

const myArr = [1,2,3]
console.log(...myArr)
console.log(myArra)

Both should work perfectly!

 
 

Hey guys, I have been working on my very first APIs project and in that project I'm making a "QUIZ APP", where from an API. I have been taking 10 question and giving them multiple choices and at end they will be getting scored. I'm using NODE.JS, EXPRESS, REQUEST, EJS for the app.

The problem comes here when i get a string from API. I change it to an object using JSON.parse() and sending it to EJS files and then displayed. but when their are symbols in question like ", ' , and more they are displayed as &139; , " like that.

                      HOW DO I FIX THAT.
 

These days, I use this a lot: console.log({ a, b });

 

That's awesome and very useful! I'm using that a lot though!

 

I never knew about console.table. Thanks for the great article!

 

You're welcome man! Yep, some console mysteries were revealed 👀

 

This was great, thank you! So nice to have options to console.log(), this will make it much easier to debug!!!

 
 

I've authored a tiny utility to easier styled console logs:

github.com/yairEO/console-colors

 
 
 

Super useful, thanks for this Guilherme!

 

You're very welcome! I'll probably bring more useful things here soon!

 

console.time also worth to mention!
Apart from that nice and concise article

 

That's true! console.time also worth the search! Good mention

 
 

Thanks for the article.. Its really awesome..
I never knew console had these many methods.

 

You’re very welcome!
Yep, console has so many things that can help us, developers!