Logging a Bunch of Values to the Console
As long as you're logging only a small amount of messages to the console, your log is likely to be readable enough. With a growing number of logging statements, however, things get messy quickly, especially if you're logging raw values without aptly named labels.
I needed to log values within a loop a while ago, which naturally led to a bunch of repeated log messages. At the end of each iteration of the loop, I would write a separator to the console to differentiate between iterations, like this:
It did the job, but it didn't feel right. What I really wanted to do is to group all logging statements issued within the current iteration of the loop. Luckily, Chrome offers a function that lets us do exactly that.
Grouping Log Messages Using
You can group related log statements by surrounding them with the
All log statements issued in between will be displayed as a group in the console view:
Notice that these grouping functions are a non-standard feature. They're supported in every modern browser, though, starting with Internet Explorer 11.
Although it's not required to pass a parameter to
console.group(), you should still do it in order to clarify what values are being grouped together. You don't have to pass the group name to
console.groupEnd() because it will always close the most recently created logging group.
Collapsing and Nesting Logging Groups
Note that the groups created by
console.group() are initially opened. If you'd rather have them collapsed by default, you can call the
Another nice aspect is that both
console.groupCollapsed() can be arbitrarily nested. That allows you to print hierarchical data to the console in a cleanly formatted manner:
// Nested group
console.group("Query String Parameters");
More Tricks for Console Debugging