Use JavaScript console.log() like a PRO
Using console.log() for JavaScript debugging is one of the most common practice among the developers even if many frown upon it. I must admit that I am still using console.log() in my day to day coding and I am not alone, like me, the majority of JavaScript developers are still using it for finding the errors in their code (Refer Developer Report — 2016). One of the main reasons for using it, its the simplest thing to do and off-course old habits die hard!
Below are the mentioned features and tips for console.log(). Click on them to directly view them.
String substitution
This is a technique which utilizes the placeholders in a string which are replaced by the other arguments that you pass to the console method. The following placeholders can be used.
- string = %s
- integer = %i or %d
- object = %o or %O
- float = %f
- apply CSS rules = %c
console.log('My name is %s, my age is %i and my weight is %f kilograms', 'Dave', 20, 60.7)
Custom CSS styles for console.log()
By default there are 4 different ways of outputting the messages to the console (log
, info
, warn
, error
). All the methods work the same way and the difference being each of them show with different color based on the log-level and different icon.
console.log('Simple Log Message')
console.info('Info Message')
console.warn('Warning Message')
console.error('Error Message')
Apart from these default functions, you can also define custom CSS styles for the logs by applying CSS rules in the string substitution with the %c
placeholder and passing the CSS rules as a string argument. You can also add more than one %c
to the string.
console.log('%c Log Message 1 with custom CSS styles! ', 'background: #555; color: yellow');console.log('%c Log Message 2 with custom CSS styles! ', 'background: black; color: red');console.log('%c Log Message 3 with custom CSS styles! ', 'background: #00f; color: white');
Another way of defining CSS styles:
const success = [
'background: green',
'color: white',
'display: block',
'text-align: center'
].join(';');const failure = [
'background: red',
'color: white',
'display: block',
'text-align: center'
].join(';');console.info('%c Success Log Message!', success);console.error('%c Error Log Message!', failure);
console.clear()
Whenever you need to clear the console programmatically, just call the clear
method.
console.clear()
Tip: You can also use Ctrl + L shortcut to clear the console and it works in all the browsers.
console.assert()
The assert
method takes two arguments, one is the assert condition and the other is the message. If the assertion is false, the message is written to the console with the log level error and also the stack trace.
console.assert(true, 'This will not be displayed')console.assert(false, 'This will be printed')
Tip: Assert method can be used for conditional logging without using the if-else block.
console.table()
The table
method can be used to display an array or an object in a tabular format in the console.
Displaying Array
var fruits = ['apple','mango','grapes','orange']
console.table(fruits);var fruits_quantity = [{
name: 'apple',
quantity: '20',
},{
name: 'mango',
quantity: '30',
},{
name: 'grapes',
quantity: '15',
},{
name: 'oranges',
quantity: '25',
}]
console.table(fruits_quantity);
Displaying Object
var details = {
"name": "Dave",
"age": 20,
"weight": 60.7
}
console.table(details)
console.trace()
The trace
method displays the stack trace that show how the code ended up at a certain point. Use the label parameter to name the trace method if using more than one trace method.
console.trace('Test Trace')
console.count()
The count
method can be used to keep track of how many times a part of the code is being executed.
for (i = 0; i < 10; i++) {
console.count('Test');
}
console.memory()
The memory
property can be used to check out the heap size status at a certain point.
console.log(console.memory)
Note: memory is a property and not a function.
console.time() & console.timeEnd()
Use the time
method to start a timer and the timeEnd
method to end the timer and display the result. You can also use the label parameter to name the time if you are using more than one timer.
console.time('Timer1');
for (i = 0; i < 100000; i++) {
// some code
}
console.timeEnd('Timer1');
console.group() & console.groupEnd()
The group
method is used to indicate the start of a message group. All the log messages after this will now be written inside the group. The groupEnd
method is used to end the message group. An optional label parameter can be used if more than one group is used.
console.log("Before Group Start");
console.group('Main Group');
console.log("Inside the group : message 1");
console.log("Inside the group : message 2");
console.groupEnd();
console.log("After Group End");
A group can also be nested inside another group.
console.log("Before Group Start");
console.group('Main Group');
console.log("Inside the group : message 1");
console.log("Inside the group : message 2");
console.group('Sub Group');
console.log("Inside the sub group : message 1");
console.log("Inside the sub group : message 2");
console.groupEnd();
console.log("Inside the group : message 3");
console.groupEnd();
console.log("After Group End");
console.profile() & console.profileEnd()
The profile
method starts the CPU profiler in the browser. The profileEnd
method is used to end the profile.You can use the optional label parameter to name the profile report.
console.profile("Profile1");
for (i = 0; i < 100000; i++) {
// some code
}
console.profileEnd("Profile1");
The generated reports can be viewed in the JavaScript Profiler tab in the developer tools.
console.dir()
The dir
method displays an object in an interactive list of properties in an hierarchical tree like structure.
var a = { foo: "foo", bar: "bar" };console.log(a)console.dir(a)
That’s pretty much all the features and tips related to console.log
! Happy Coding!