Last week I shared three handy dev tools that let us format our console outputs beyond the plain-old console.log()
. Today I learned one more neat trick to "prettify" our console.
This trick is so simple, all you need to do is add a special indicator inside your console.log()
.
Let's see how it works with pure strings:
- Add this set of characters,
%c
, at the start of the string. - Pass in an additional argument, which contains the style of the string. As you can see below, the syntax is basically the style attributes of an HTML element.
That's it! Feel free to play around on your browser console:
console.log('%c Style me pretty 💋', 'font-family: "Impact", sans-serif; font-size: 100px; color: black; background: #ffc600;')
Now to the practical use.
Say you want to test how a variable, lastChecked
, gets reassigned inside a function. Aside from writing out the current output of the variable in your console.log()
, you can insert the styling as an argument, like so:
console.log('%c lastChecked before shiftKey: ', 'color: black; background: #BADA55;',lastChecked)
console.log('%c lastChecked inside shiftKey: ', 'color: black; background: #FFC600;', lastChecked)
console.log('%c lastChecked after shiftKey: ', 'color: black; background: #3EA055;', lastChecked)
Just like that, you are presented with a colorful console log with clear distinctions between different stages. It is a cool alternative to organizing your console outputs, similar to the console.group()
method as mentioned in my previous post.
Finally, you might be wondering how I found out about those little tricks.
In addition to the wonderful search engine, I have been coding along with the popular, FREE JavaScript30 tutorial by Wes Bos, who kept introducing fascinating dev tools along the journey and creating a fun, delightful JavaScript learning experience.
I highly recommend checking it out if you haven't already.