0
0
JavascriptHow-ToBeginner · 3 min read

How to Use console.group in JavaScript for Organized Logs

Use console.group() to start a new group of related log messages in the browser console, making them collapsible. Call console.groupEnd() to close the group. This helps organize logs visually and makes debugging easier.
📐

Syntax

The console.group() method starts a new indented group in the console. You can optionally pass a label to name the group. Use console.groupEnd() to close the current group.

  • console.group(label): Starts a new group with an optional label string.
  • console.groupEnd(): Ends the current group.
javascript
console.group('Group Label');
console.log('Message inside group');
console.groupEnd();
💻

Example

This example shows how to group related console messages under a named group. The group can be expanded or collapsed in the browser console.

javascript
console.log('Start of logs');
console.group('User Details');
console.log('Name: Alice');
console.log('Age: 30');
console.group('Address');
console.log('City: New York');
console.log('Country: USA');
console.groupEnd();
console.groupEnd();
console.log('End of logs');
Output
Start of logs ▼ User Details Name: Alice Age: 30 ▼ Address City: New York Country: USA End of logs
⚠️

Common Pitfalls

Common mistakes include forgetting to call console.groupEnd(), which can cause groups to remain open and confuse the log structure. Also, nesting groups too deeply can make logs hard to read.

Always balance each console.group() with a matching console.groupEnd().

javascript
/* Wrong: Missing groupEnd() */
console.group('Missing End');
console.log('This group never closes');

/* Correct: Properly closed group */
console.group('Proper Group');
console.log('This group closes');
console.groupEnd();
📊

Quick Reference

MethodDescription
console.group(label)Starts a new console group with an optional label.
console.groupEnd()Ends the current console group.
console.groupCollapsed(label)Starts a collapsed group, closed by default.

Key Takeaways

Use console.group() to start a named group of related console messages.
Always call console.groupEnd() to close the group and keep logs organized.
Nested groups help structure complex logs but avoid too deep nesting.
Groups can be expanded or collapsed in the browser console for clarity.
Use console.groupCollapsed() to start a group closed by default.