DEV Community

Anand Kumar
Anand Kumar

Posted on • Edited on

Sharpen your `console` axe in javascript for better logging

As a beginner or even as a advance web developer, we tend to use console very frequently while development or debugging. Most of the time we use console.log() to output the value for any of our variables/functions etc.
Though there are some other nice handy methods available with console along with some enhancements that we can do with existing one.
So, more frequently used console methods are following:

  • console.log()
  • console.error()

And, other methods that I am going to explain in this article are following:

  • console.dir()
  • console.table()
  • console.count()
  • console.group()

We will go into the details of each of these methods one by one below. So, lets get started without any further delay.

console.log()

This method is used the most yet more often we do not know what all it holds. Most of the time we use it as console.log(theObject) or we also do something like
console.log(theObject, theOtherObject, aString).
There is one more format that we can use is console.log(theMessageToPrint, theObjectOrValuesToPrint).

console.log('I like the new way of using %s', 'console.log');
// OR
console.log('Hello %s and %s, how are you doing?', 'Foo', 'Baz');

The output of the above console.log would be:

> I like the new way of using console.log
// OR
> Hello Foo and Baz, how are you doing?

Common placeholders that we can use are:

  • %s Takes string
  • %o Takes an object (That is not zero)
  • %d It is for a decimal or integer

So, lets see one example having all these three:

console.log('+%d for %s and %o to have methods which helps in debugging.', 10, 'JavaScript', window.console);

Here is the output.

console.log() output with placeholders

Now, comes the most interesting placeholder (at least for me) %c. This placeholder is for CSS values. Which means, putting some colours to our console output text.
Let's see by example:

console.log('Hello red %cButton', 'background-color: red; color: white;');

console.log() %c placeholder in action

But, is it useful??? Put your thoughts in comments sections.

console.error()

This one is similar to console.log() except that it shows the text output in red with light red background with a cross icon at the far left. Example is given below.

console.error('I am error console and supports the features of "console.log()" with some added styles by default');

console.error()

console.warn()

This one is again similar to console.log() except some default styles. With warn(), we get yellow text color with light yellow background. It also gets an exclamation icon at the far left.

console.warn()

console.dir()

While this works similar to log() but a bit different. When using dir(), the output is more objecty way of looking at the output. It is more effective when we use it on html elements.
Check the example given below.

console.dir()

In the screenshot above, I have created an html element using document.createElement(). Then, did console.log() & console.dir().

The difference is visible. So, sometimes we may need to look into the output the way dir() is presenting. Go ahead, and explore it.

console.table()

As the method name suggests, it is output the data in tabular format. The output becomes much neater and readable in comparison of simple logging for array.
Lets see the following list of data:

const users = [{
    id: 'user_1',
    fName: 'Anand',
    lName: 'Kumar',
    displayName: 'AnandK'
}, {
    id: 'user_2',
    fName: 'Aarav',
    lName: 'Jha',
    displayName: 'AaravJ'
}];

What we usually do to console this data? We do console.log(users). Let's see what output it gives with console.log().

▶ (2) [{…}, {…}]

The above output shows us that it is an array with 2 data. The little arrow at the left helps us to look into it in more detailed view.
But, if we console the users array using console.table(users), the output looks more helpful as shown below:

console.table(users)

The console.table() also has a second argument which we can use to have the output with selected columns only.
Let's have a look.

console.table(users, ["id", "displayName"])

And here is the output.

console.table(users, ["id", "displayName"])

Each header in the output table is interactive and can be used to sort the data as well. In the above screenshot, you can see an arrow at the right hand side of displayName column as an indicator when you interact with the column for sorting.

console.count()

This can be handy when we want to do some named counter. Let's say, we want to know the number of times an execution happened, we can use the count() to know exactly the same thing.
Let's look at an example.

for(let i = 0; i < 10; i++){
    if(i % 2 == 0)
    {
      console.count('Even number');
    } else {
      console.count('Odd number');
    }
}

And the output of the above will be like this:

Even number: 1
Odd number: 1
Even number: 2
Odd number: 2
Even number: 3
Odd number: 3
Even number: 4
Odd number: 4
Even number: 5
Odd number: 5

So, we can see above that with the console statement, it is also giving us a count for that particular output which depicts number of times, it is called.
By any chance, you want to reset the count, there is method called console.countReset() which will reset the count. Example:

console.countReset('Even number');

Please note that when using countReset(), make sure the text inside is same for which we want to reset the counter.

console.group()

Last but not the least, group(). As the name suggests, we can use this to group the console items. This means, we can nest the console items and make it look like one group. Let's have a look at it by implementation.

var counter = 0;
console.group('Outside code block');
console.log('counter is ', counter);
console.group('Loops...')
for(var i = 0; i < 10; i++){
    console.log('Looping for ', i);
    counter++;
}
console.groupEnd();
console.log('Total count: ', counter);
console.groupEnd();
console.log('All console completes here');

The output of the above code block is here.

console.group()

Here, we also used something called console.groupEnd(). This is used when you want to end a particular group. The output is always expanded(by default) when we use group() but if we want it collapsed, there is an alternate method called groupCollapsed() which results in the same output but in collapsed mode. This can be helpful if we do not want to show everything expanded for any grouped output in our console.

Conclusion

Do we really need to have a conclusion here. :)
Anyway, all of these methods are useful if you want something more than just console.log(theObject).
I find, console.table() very useful among these but others can be useful at times and so no harm in keeping it in our arsenal for logging the relevant information.

There are other methods available with console which you can explore at your own. Here is the link to specification: https://console.spec.whatwg.org

And, show some love and do like and follow for more of such tutorials.

Top comments (0)