11
Console API - Debugging Like A PRO - Javascript
Console API of Javascript scripts provide a lot more than just console.log
. Here are some of my observations & learning on the **Console API. Also, a few tips that I use for logging are added at the end - Feel free to stick till the end.
This is what is used by most developers to print something in the developer console. But there are a few more console methods that could improve our development experience. Some of them are below,
- debug => same as log, but has a log level of
debug
. - error => same as log, but has a log level of
error
& add red background to the message. - info => same as log, but has a log level of
info
. - warn => same as log, but has a log level of
warn
& adds blue background to the message.
*Syntax: *console.log(obj1 [, obj2, ..., objN]); console.log(msg [, subst1, ..., substN]);
Ever confused about how many times the recursive call or a loop is executed? count
method of the Console API covers this.
*Syntax: *console.count('label')
When the group method of Console API is called, the subsequent logs are printed in a group. Also, we can use a group inside a group to create an inner loop. The groups are ended when the console.groupEnd()
is called. Additionally, if you want your groups to be collapsed, you can use console.groupCollapsed()
instead of console.group()
.
This could be super useful when you have a log statement in a function and you can surround the function caller with group and group end to differentiate the results.
*Syntax: * console.group([label]);console.groupCollapsed([label]);console.groupEnd([label]);
console.dir
& console.table
are used for clear representations of object properties and array element properties more clearly.
*Syntax: * console.dir(Object);
console.log(Array<Object>);
console.time
is used to register a timer to track in the global level and whenever we need a time elapsed during the execution, we can call console.timeLog()
. Also to end a timer, we can call console.timeEnd
. We can run multiple timers by passing a label param to the console.time([label])
method.
*Syntax: * console.time(label);
console.timeLog(label);
console.timeEnd(label);
I usually have the habit of appending the name of the variable while logging the value to the console. The following helped a lot of time during various debug sessions. Hope you find this useful.
Hope you find this useful. If there are any tip and trick for logging, please add in the comments. Let me know if it could be improved in the comments and feel free to follow on Twitter - radnerus93
11