console.log the cool way
- Published on
Logging the old-fashioned way
As someone who writes JavaScript every day, console.log()
is a method that's always in my toolkit. It's one of the easiest and quickest way to debug something.
console.log('Hello World')
Hello World
This is cool for simple text, but what happens when you want to log a bunch of variables?
Not very intuitive. Specially when the data comes from an API and you have no clue which variable is holding what data.
Logging the 'cool' way
There are a few more default logging levels apart from console.log()
, such as console.debug()
, console.info()
, console.warn()
and console.error()
. All of these are self-explanatory. We'll look at some more fancy console
methods below.
Who's who?
Let's log the variables foo
and bar
, but this time by wrapping them in an object syntax.
Now we can easily identify the objects by their name.
Tables are in fashion
console
object has a table
method that prints data in a neat table. Let's log some
Everything is better in a group
Sometimes we want to group together a couple of log statements which are inter-related. That's where console.group()
shines.
To start a group, use console.group(${groupName})
, and to end a group console.groupEnd(${groupName})
. The browser console will now wrap all the logs we have between the group in a collapsible section.
You can also use console.groupCollapsed()
instead of console.group()
if you want the groups to be collapsed by default. You would need to hit the expand button on the left to see the logs within the group.
Fancy some colors?
We can also use style our logs by using %c
directive. This can be used to differentiate between different status, or callers by creating a wrapper function.
How fast are you?
There are some instances where you'd want to see how much time a piece of code took to execute. console.time
comes handy to print the time.
A lot more stuff
There are more advanced console
methods like assert()
, clear()
, count()
, countReset()
, dir()
, dirxml()
, timeEnd()
, timeLog()
, trace()
. You can always log the console object itself to check all supported method in the browser.
Conclusion
Using console.log
is a great way to visualize things and debug your code. By making use of the extended console
methods, you can improve the efficiency of that visualization and be more productive. Some would argue that console
is not the way to debug things, and you should use a proper debugger to check values and analyze the stack strace, but if something simple like a console.log
can make your life easier, why go for the complex solution?
I've been using console.log
for over a decade, and I will keep on using it as long it keeps me productive.
Let me know in the comments below what console methods are your favourite.
Until next time! ✌🏽
On this page