Console.log() - The Right Way โ
An 'Array' of Features You Probably Didn't Know Existed
๐ Hi
In this post we are going to learn the hidden secrets behind the console in JavaScript. Logging messages to the console is an awesome way to diagnose / troubleshoot errors in your code. To enter the javascript console Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) or right-click inspect element then navigate to the console tab. Let's get started...
Console.log() โ๏ธ
This is the most simple example of using the console, you can put any type inside of the log()
ie. String, Boolean, Array, Object etcโฆ
Console.log( {x, y, z} )๐งฎ
I bet that youโve atleast used console.log(โThe value of x is โ + x)
at least one time before. Now imagine you had to do this for 3,4 or even 5 values. Your code becomes hard to maintain and read but did you know by using curly braces you can make an association between a logged value and a variable name. You can also do this with single variables with console.log({b})
Template Literals ๐
Although this isnโt a feature strictly reserved for logging template literals allow you to embed expressions, we enclose them with (`) backticks instead of (โdoubleโ) or (โsingleโ) quotes. The expressions are indicated by the dollar sign followed by curly braces
${expression}`. ATOW these are still not supported on Internet Explorer.
You can also do multiline strings with them without having to use \n
, this can improve the readability of your code.
Fancy Formatting ๐ด๏ธ
An alternative to using template literals
is sprintf()
for JS. This is an older method of using variables in JavaScript (pre ES6) so I still recommend using template strings. The table below shows how each object is casted.
Specifier | Purpose |
%s | Converts to String |
%d or %i | Converts to Integer |
%f | Converts to Float |
%o | Optimally Useful Formatting |
%O | Generic JS Object Formatting |
%c | Applied CSS |
Even Fancier Formatting ๐ฏ
We can apply styles to logged messages, we can do this by using %c
with the CSS style you want to apply.
We can even go crazy with some awesome CSS styling, in this example, I stored the CSS in a variable and then console.log("%cOoshimus.com %s", css, 'rocks!');
Interactive Logs ๐
Depending on the browser the logs are rendered differently whilst Firefox and Chrome allow for more interactive logs, Node outputs the console using texts. Chrome allows you to expand and collapse different logs ie. arrays
. In the example, you can see the object properties and prototypes.
Here is more on prototypes if you donโt know what they are.
Arrays ๐ ๐๏ธ ๐
We can also use arrays to show an expandable / collapsible list.
Closing Up ๐
I hope that you learnt something new here, if you have any other cool tricks that you can do in the console please comment down below. Also, please reach out on LinkedIn .