Use console.group for better JavaScript debugging

For debugging JavaScript/jQuery code, the easiest and preferred way is to use console.log() to output a message in web console. But it works fine when you have small amount of logging message. But having large number of logging makes log messy and unreadable.

console.group() can be used to group related log messages and use console.groupEnd()to close the group. Like,
console.group("Func 1 start");
console.log("Loop start.");
console.log("i:" + i);
console.log("Loop end.");
console.groupEnd();
And below is the output in console window. The log message are displayed within a group.
Console Group Message

You may also like:
This is quite useful when you are debugging multiple functions at same time and then using console.group() you can easily group them function wise.

Another nice feature is that you can also nest groups which allows to output message in hierarchical manner.
console.group("Func 1 start");
console.log("Loop start.");

//Nested Group
console.group("In Loop");
console.log("i:" + i);
console.groupEnd();

console.log("Loop end.");
console.groupEnd();
And below is the output in console window.
If you see the output, all the groups created as open by default. console.groupCollapsed() allows you to create collapsed group by default. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. And call console.groupEnd() to back out to the parent group.
console.groupCollapsed("Func 1 start");
console.log("Loop start.");
console.log("i:" + i);
console.log("Loop end.");
console.groupEnd();
Few things to note.
  • Its not compulsory to pass group name in console.group() and console.groupCollapsed() but you should pass the group name to find out what message are being grouped together.
  • Don't pass group name to console.groupEnd() because it will always close the most recently created logging group.

Hope you find this useful. Happy debugging!!!!!
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..