Grouping console.log() Output

console.log()

If you’ve ever touched JavaScript in your life, you’ll no doubt know about console.log() for debugging. It allows you to log debug information to the console (on most browsers).

The problem

If you log large amounts of debug information, it is hard to interpret your console output effectively. In fact, you probably make this even worse by wrapping even more debug information around what you’re looking for, to help identify it! e.g.

1
2
3
4
console.log("MY GROUP");
console.log(info1);
console.log(info2);
console.log("MY GROUP END");

The solution

console.group()

Using console.group() allows you to (go on, guess) group your console output:

1
2
3
console.group("My group");
console.log(info1);
console.log(info2);

console.groupEnd()

Using console.groupEnd() allows you to terminate logging to the currently defined console group:

1
2
3
4
console.group("My group");
console.log(info1);
console.log(info2);
console.groupEnd();

console.groupCollapsed()

The big hitter, collapse your group by default with console.groupCollapsed() instead of console.group():

1
2
3
4
console.groupCollapsed("My group");
console.log(info1);
console.log(info2);
console.groupEnd();

Objects and arrays

console.table()

If you’re logging objects and/or arrays in your groups, there’s another winner for you in the form of console.table():

1
2
3
4
5
6
console.groupCollapsed("My group");
console.table({
info1: { message: "message 1" },
info2: { message: "message 2" }
});
console.groupEnd();

Console Output

See the jsfiddle here - ensure you open the console, then click run.

Happy, clean debugging!