JavaScript console provides multiple useful methods, which if used effectively can greatly help with your development. Here is the list of most useful methods and console tricks.
Print/Sort/Filter the array or object in tabular format
You can print the array or object (even received from an API call) into a nice easy to understand table format. console.table(data, [filter_columns])
method provides the functionality to print, filter and sort the data in easy manner. To sort you can click on header of the table in console.
Clear console before logging
If there are too many logs already and you find difficulty in debugging. You can always clear your console by using console.clear()
method before any logging. Always remember to remove it after your specific debug is done.
Print complete stack trace of method call
console.trace()
method will print the complete stack trace of method call which helps in determining the source of method calls, this is one of the very useful debugging tool.
Filter console log using log levels
Everyone is familiar with the overused general log method console.log()
but there are plenty available which will help you in better filtering of logs if properly used. These are warn
, error
, info
, debug
. Based on browser they may be in different color and with or without icons
Count no of times a method is called
console.count()
can be used to count the no of times a method has been called. it can be used as a named counter by passing in the name as parameter. To reset the count call console.countReset()
with same name
Test or Assert a value
console.assert()
Logs a message and stack trace to console if the first argument is false.
Group all the console logs of a method or class in a section
console.group()
/ console.groupCollapsed()
creates a new inline group, indenting all following output by another level. To move back out a level, call console.groupEnd()
.
Measure function execution duration
Track and measure the duration/time of a function call and its performance using JavaScript console. The method to start the timer is console.time()
, To log the time passed console.timeLog()
and to stop the timer console.timeEnd()
See it in action below. You can pass some name as parameter also to make it Named Timer.