As web-developers, we spend a lot of time using browser developer tools. But some of us are not aware that this tool is way more powerful than we think. Today I'll show you some simple, useful and cool tricks that you can start using right away. All of the examples work in all recent browsers.
console.log is probably the most used command along with the debugger. But did you know that there are several warning levels that you can print out to the console? Check them out:
console.debug('This is the regular log output');
console.info('Informational message');
console.warn('Warning! It might be dangerous');
console.error('Error with some tracing');
It is recommended to use the $log service in AngularJS, though. It does all of the above, but you can disable the output to the console for production with $logProvider
:
angular.module('App', [])
.config(function($logProvider) {
$logProvider.debugEnabled(false);
})
.run(function($log) {
$log.log('This will not be shown');
$log.error('You will not see this error too');
});
Did you know that you can style your output to console with CSS? It is very easy to do:
var styles = 'background: #f00; color: #fff; padding: 0 100px; font-size: 20px;';
var message = "Can't miss that out";
function styledMessage(message, styles) {
$log.log("%c" + message, styles);
}
Note that styles should be passed as a string, without curly braces ({}
).
Sometimes it is handy to check how many times a function is called. There is an easy way to do this with the console API:
function reloadData() {
console.count('Data reloaded');
// ...function body omitted...
}
This simple trick can really help debug a problem and optimize performance.
The Console API also allows us to measure time between two points of execution:
console.time('for loop');
var a = [1,2,3,4,5,6,7,8,9,10];
var sumA = 0;
for (var i=0; i<a.length; i++) {
sumA += a[i];
}
console.log('A: ' + sumA);
console.timeEnd('for loop');
console.time('reduce');
var b = [1,2,3,4,5,6,7,8,9,10];
var sumB = b.reduce(function(prev, next) {
return prev + next;
});
console.log('B: ' + sumB);
console.timeEnd('reduce');
This comes in handy for debugging and optimization, when we want to check exactly how long it took for a block of code to run.
console.dir prints a JavaScript representation of a given object. It comes in handy with HTML elements, since it output its DOM representation properties.
console.dir(angular.element('body')[0]);
There are plenty more console tricks available to you, and I encourage you to read the Console API Reference on the chrome developer website. You can find out how to start the profiler, add timestamps to the timeline and more.
There is also a great free course from CodeSchool called Discover Devtools. While it is most useful for beginners, I think it would be useful for many experienced developers as well.
Always improve your knowledge of the tools that you use every day, and share your discoveries with others!