Much more than a console.log!

Many of us usually use the console API just with its well known console.log(variable) method to get the value of a variable in certain lines of code. but actually the console API of the DevTools offers you much more access through your code’s heart than a simple value logging command.

The log

The log method accepts several arguments from almost all types of data to show their values together:

console.log(‘sample string’, num, ‘with object:’, obj, ‘and array’, arr.length, ‘and methods’,;
// ‘sample string’, 12, ‘with object:’, {name: ‘ali’}, ‘and array’, 12, ‘and methods’, 1436478290841

and also you may separate types of logs according to case with:

console.warn(‘the value exceeds!’, num);
console.error("Error: %s (%i)", "Server is not responding",500);'The rare condition happened');

The warn method prints the result with a yellow warning icon and the error prints the result in red and with extra information.
Using warn, error, info and log methods improves the readability of logs when you have a vast amount of them in your DevTools by filtering them using tab views.


This method comes really handy when you need to log series of data for multiple time and track the changes. A practical example would be ReactJS middle-wares. Assume this logger:

const logger = store => next => action => {'dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result

The result will be some thing like:

Which is so neat and I think I’m safe to say so far it has saved hours and hours of my debugging time.

The pie time!

There is another method which helps you to check the elapsed time for running a code block: time method.

// code block
// retunes result in ms

Comparing the duration of a single code block with and without a console.log() command in it, makes you remember to always remove the logs in distribution version.

function unbalancedRandom (n) {
var x = Math.pow(Math.random() * n, (Math.random() * 0.98 + 0.01));
var r = (x >= 1) ? x — 1 : x;
console.log(‘RAND’, r); // this is the logger command
return r;
for(var i =0; i < 100000; i ++) {
var t = unbalancedRandom(16);
if (t >= 16) {
console.warn(‘returned equal);

Running this code part without logger command takes 148ms while running it while the logger command exist in the function result the 11944ms runtime duration.

Using methods of console API in your code, besides the advantages briefly discussed above, causes a notable drop in speed of your code, so it’s recommended to remove them if they’re not necessary for the distribution version.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.