Cover Image for Javascript Console API: The best bits

Javascript Console API: The best bits

Beyond the ever-handy 'log', there are a few highly useful methods you can use.

Table

Firstly there is table. It can return a nicely formatted visual representation of complex objects or arrays.

1 console.table(twistedObject);

Time

Wrapping your code in 'time' and 'timeEnd' can act as a rudimentary timer, for you to establish the speed of your processes.

1 console.time("nestedLoop");
2 for (let i = 0; i < 10; i++) {
3 for (let j = 0; j < 10; j++) {
4 console.log(i, j);
5 }
6 }
7 console.timeEnd("nestedLoop");

This will return something like: nestedLoop: 8.526ms

Trace

You can perform a stack trace with 'trace'.

1 const findMe = () => console.trace(‘Where am I?);
2 findMe()

And because 'log' does really reign supreme, here are a couple of tips with it:

Computed property names

Here's a handy ES6 trick: if you want to print out the name of your variable attached to its value, wrap your variable in curly braces:

1 console.log({ myArray, myObject, myString })
2
3 // OUTPUT
4 { myArray: [ 123, 666, 1, 0 ],
5 myObject: { '1': 'Tofu', '2': 'Toothpicks', '3': 'Ecstasy' },
6 myString: 'All the way down' }

CSS styling

To prettify your monotonous monotone screen, you can insert CSS into the browser console.

1 console.log("%c Whatever", "color: goldenrod; font-size: 4rem;");

Here's a link to the MDN Dev Docs for a thorough investigation of all console's methods