The JavaScript Console or the Console Object provides access to the browser’s debugging console. Chrome’s debugging console is DevTools Console and for Firefox it is Web Console. It is available in browser’s Window scope
Basic Logging
Let’s start by looking at the basic logging methods.
console.log('This is log');
console.warn('This is a warning');
console.error('This is an error');
console.info('This is info');
console.debug('This is debug');
This will log the following messages in the console:
console.log vs console.debug
In Chrome, console.debug
will show in blue but console.log
will be shown in black. The color is the only difference as far as these two methods concerned.
You can filter the log messages by selecting the dropdown above the console window:
You can pass in values as a comma delimited array as well. These values will be logged out separated by a space.
console.log('This', 'is', 1, 'log');
This will be logged out like a usual message:
String Substitution
If the first argument starts with a string, we can use string substitution like in C language.
console.log('The %s has %d moon(s)', 'Earth', 1, {name: 'Moon'});
The result in console:
CSS Output
By prefixing %c
to a string, we can print CSS into the console!
console.log(
'This looks %cfansy!',
'color: hotpink; font-size: 30px; border:1px solid black; padding: 2px'
);
The result in console:
Grouping and Nesting
We can group log output into collapsable hierarchies using console.group()
.
console.groupCollapsed('Fruits');
console.groupCollapsed('Green');
console.log('Apples');
console.log('Pears');
console.groupCollapsed('Yellow');
console.log('Bananas');
console.log('Pineapple');
console.groupEnd();
The result in console:
Assertion
We can use console.assert
, which is syntactic sugar for logging an error to the console when a given condition is not met.
var something;
console.assert(something, 'something is not defined!');
The result in console:
Counting Events
By using console.count
we can count the number of times something was logged.
for(var i = 0; i < 10; i++) {
if(i < 6) {
console.count('less than 6');
} else {
console.count('greater than 6');
}
}
The result in console:
Timing Data
By using console.time
with console.timeEnd
to get accurate timings of operations in javascript.
var i = 0;
console.time('looping');
while(i > 1000000) {
i++;
}
console.timeEnd('looping');
The result in console:
Tabular Data
Using console.table
to render arrays and objects in a tabular format.
var fruits = [
{ name: 'Apple', color: 'Red'},
{ name: 'Pear', color: 'Green'},
{ name: 'Banana', color: 'Yellow'}
];
console.table(fruits);
The result in console:
Conclusion
These console techniques will definitely help you to make your console logs look more interesting.