When it comes to debugging code, there are many options, but I find myself relying on console.logs quite often.
It's a quick and complete way to log a data set at a certain point or see where the code returns.
By all means, it may not be the best way, but it's widely used.
Did you know you can do more than a plain console.log?
Grouping console logs
A super handy console command is to group-specific logs.
You can easily start a new group with console.group('name')
and end it with console.groupEnd('name')
.
The name of the group can be any string you would like it to be.
An example can look like this:
console.group('test group');
console.log('log line 1');
console.error('Something went wrong in the group');
console.groupEnd('test group');
This will show up as:
Console log a table
Ever needed to display a giant JSON array? It can be tedious the show a larger array in the console.
But there is an option to display this as a table.
const myArray = [
{
title: 'Article 1',
views: 400,
url: 'https://daily-dev-tips.com/article-1'
},
{
title: 'Article 2',
views: 6500,
url: 'https://daily-dev-tips.com/article-2'
}
];
console.table(myArray);
Console count
Another super useful command is the console.count
command.
It can be used to count how often a loop is run, for instance.
for (let i = 0; i < 5; i++) {
// Do something
console.count('loop one');
}
You can provide a label as we did above.
Console log/info/debug/warn/error
Besides your default console.log, you might want to show data a little differently. Hence you can use one of the following to make it appear so:
console.info
console.debug
console.warn
console.error
They will show up like this:
Note: The info used to have its own icon but seems to be mixed with a regular log now.
With these, you can easily filter on the different levels.
Other console commands
There are some other console commands that can be useful.
And some we might cover in a later stage:
- console.assert
- console.dir
- console.trace
- console.clear
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or [Twitter](twitter.com/DailyDevTips1