DEV Community

Guilherme Toti
Guilherme Toti

Posted on • Updated on

Stop using default console.log, check this instead

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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`;
Enter fullscreen mode Exit fullscreen mode

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}`);
Enter fullscreen mode Exit fullscreen mode

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;');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

Viewing DOM Elements

Let's say you have something like:

const p = document.querySelector('p');
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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`);
})
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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!

Oldest comments (45)

Collapse
 
kendalmintcode profile image
Rob Kendal {{☕}}

Super useful, thanks for this Guilherme!

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
maciejcieslik profile image
Maciej Cieslik

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
salyadav profile image
Saloni Yadav

What does trace do?

Thread Thread
 
guilhermetoti profile image
Guilherme Toti

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)
Collapse
 
namstel profile image
Namstel

Oo! I like that one a lot. :)

Collapse
 
nicknds profile image
NIku Nitin

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
darryl profile image
Darryl Young

Thanks for sharing, Guilherme.

Collapse
 
guilhermetoti profile image
Guilherme Toti

You’re welcome!

Collapse
 
robrecord profile image
Rob Record

Great, thank you for this!

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
rubenwap profile image
Ruben Sanchez

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!

Collapse
 
guilhermetoti profile image
Guilherme Toti

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!

Collapse
 
willydee profile image
Willy Schott

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

Thread Thread
 
guilhermetoti profile image
Guilherme Toti

ahahaha

Collapse
 
pvcodes profile image
Pranjal Verma

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.
Collapse
 
sidwarkd profile image
Kevin Sidwar

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.

Collapse
 
guilhermetoti profile image
Guilherme Toti

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)

Collapse
 
sidwarkd profile image
Kevin Sidwar

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

Thread Thread
 
guilhermetoti profile image
Guilherme Toti

ahahaha! you're welcome!

Collapse
 
julianeon profile image
Julian Martinez

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
rafaelrferreira profile image
Rafael R. Ferreira 🕹️🐕

awesome tips!

Collapse
 
guilhermetoti profile image
Guilherme Toti

Thanks man!

Collapse
 
foksa profile image
Djordje Radakovic

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

Collapse
 
salyadav profile image
Saloni Yadav

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. :)

Collapse
 
guilhermetoti profile image
Guilherme Toti

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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
Collapse
 
sarahb831 profile image
sarahb831

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

You're welcome!

Collapse
 
anandprem333 profile image
Anand Prem • Edited

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

Collapse
 
guilhermetoti profile image
Guilherme Toti

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