DEV Community

Cover image for Console API - Debugging Like A PRO - Javascript
Suren
Suren

Posted on

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.

1. console.log & similar ones

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]);

console-logs-and-variations.png

2. console.count

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')

console.count.png

3. console.group

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.group (2).png

4. console.dir & console.table

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.dir.png

Untitled design (1).png

5. console.time

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);

console.time.png

Smart Logging

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.

tip.png

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

Top comments (0)