Grouping Console Logs

Published: Monday, June 20, 2022
Updated: Tuesday, August 9, 2022

Greetings, friends! As you may know, the console.log function is basically a web developer's best friend. However, best friends can occasionally get disorganized. If you're debugging an application with too many console.log statements, your environment's console could become cluttered. Luckily, the console.group and console.groupEnd functions exist to help organize our logs!

Let's look at an example. If you're using Google Chrome, then you can open up the Chrome DevTools console using the keyboard shortcut Option + Command + J on a Mac or Ctrl + Shift + J on Windows. Copy the following code into the console and hit Enter.

javascript
Copied! ⭐️
console.log('I am outside a group');
console.group('food');
console.log('pizza');
console.log('donut');
console.log('potato');
console.groupEnd();
console.log('I am also outside a group');

You have now created a group called food where each console.log statement in that group is indented and in a collapsable dropdown. The console.groupEnd function signifies the end of the group. You can click on the arrow near the group name to collapse or expand the dropdown.

Initially, the dropdown for each group will be expanded. If you want the dropdown to initially be closed or collapsed when you run the code, then you should use console.groupCollapsed instead of console.group.

javascript
Copied! ⭐️
console.log('I am outside a group');
console.groupCollapsed('food');
console.log('pizza');
console.log('donut');
console.log('potato');
console.groupEnd('food');
console.log('I am also outside a group');

If you don't provide a name by default, then Google Chrome will set the default name of that group to console.group.

javascript
Copied! ⭐️
console.log('I am outside a group');
console.group();
console.log('pizza');
console.log('donut');
console.log('potato');
console.groupEnd();
console.log('I am also outside a group');

You can create groups with different labels to help organize your log statements. In the code below, we are creating two groups: one with the label, food, and the other with the label, drinks.

javascript
Copied! ⭐️
console.log('I am outside a group');
console.group('food');
console.log('pizza');
console.log('donut');
console.log('potato');
console.groupEnd();
console.log('-------------------------');
console.group('drinks');
console.log('water');
console.log('milk');
console.log('apple juice');
console.groupEnd();
console.log('I am also outside a group');

Doesn't that look much nicer! The console.group function just became our tidy friend who helps keep everything clean 🙂