Lesser Known Features of the Browser Console
The browser console is a frontend developers best friend.
While we are all aware of the basic methods like console.log()
, console.warn()
, console.debug()
, or console.error()
, are you aware of some of the lesser known, but still powerful, features?
Let's dive in!
Grouping Output
With the console.group()
, console.groupCollapsed()
, and console.groupEnd()
methods, we can easily group console output within collapsible groups and subgroups.
console.group( groupName )
Starts a new group with the supplied name.
console.groupCollapsed( groupName )
Starts a new group with the supplied name that is collapsed by default.
console.groupEnd()
Ends the current console group.
String Substitutions
When using console.assert()
, console.log()
, console.info()
, console.warn()
, console.error()
, or console.trace()
, you can use string substitution within the message that is passed into the method.
%o
or %O
- JavaScript object
%d
or %i
- Integer (Number formatting is supported, only in Firefox and Safari, per my testing)
%s
- String
%f
- Floating-point value (Number formatting is supported, only in Firefox and Safari, per my testing)
Styling Console Output
Using the %c
specifier in strings allows us to apply styles to console output. The output string in the first parameter has the style rules in the subsequent parameters applied to it in their respective places in the string.
Assertions
Using console.assert()
you can validate an assertion and write an error message to the console if the assertion fails.
Counting Instances
Using console.count()
you can create a simple counter that will count the number of times it is called with the specified label.
And with console.countReset()
, you can easily reset that counter.
Browser Profiling
With the console.profile()
and console.profileEnd()
methods, you can easily run some JavaScript profiling.
Where the profiling data is displayed depends on the browser being used.
In Firefox, you'll find the profiling data within the Performance tab in the developer tools.
In Chrome, you'll find the JavaScript Profiler tab by navigating to the three-dot menu -> More tools -> JavaScript Profiler.
And the data is displayed in the main frame of the developer tools.
It should be noted that this feature is not standard in the specification, so do not use it in production at all.
Formatting Tabular Output
You can format an object as tabular data very easily using console.table()
!
You are able to pass any primitive values here also, but they render like how console.log()
does.
Objects are where this method really shines.
Stack Trace
Wth the console.trace()
method, we can print a stack trace to the web console.
You can also pass in data parameters and they will be formatted like console.log
is.