The next set of tricks were around the console object. The first one was that you can style output to the console with
%c . It looks like this:
console.log('%c This will be red and large', 'color: red; font-style: italic; font-size: 3em;')
Putting the code above into the console or in your code will print out the message in large red italic text. Of course you can use whatever other CSS attributes you want. It may not be something I use too regularly, but it’s good to know that you can.
One other trick that I think was touched on during an earlier day, was that you can interpolate values into a console.log. I remember trying to figure out what works but not having a ton of luck Googling it. You can use
%s for string or
%s). This one looks like this:
const fire = 'hot'; console.log('The fire over there is %s!', fire);
Interpolation will make the message print out “The fire over there is hot!”. Anyone familiar with sprintf or related functions should have no issue undeerstanding what works, but as I mentioned, it’s a tiny subset of what you can use with
The next few tips, I’ll just mention as they were not new to me, but he talks about
console.info as ways to make console messages a little more useful and interesting to look at. There’s also console.assert which works in a way that anyone with assert or similar in their language of preference should be familiar with. The first argument is something that should evaluate “truthily”. If it doesn’t then it prints the second argument to the console as an error message. Think of it like a tiny inline unit test.
console.clear() which wipes out the console’s contents. I’ll still probably stick to clicking the button and can guess I’ll probably never write that into any code.
console.dir was next and I feel like this has also been touched on in the last few days too. It works in a way similar to console.log on a value, but instead of printing out the value of the value, it can tell you the properties and methods on that value. If you want to know about all the functions that
console has, for instance, you could do
Next up was
console.log. There’s also
console.count() which allows you to keep track of… something. Every time it’s called, it will tell you the current number of times you’ve called it with a particular argument. I’m sure it could be very useful for some use case. It’s not one I go for almost ever, though.
console.time which allows tracking of timers with a name. Like
console.count you can set a number of timers with names, and whenever you make the corresponding
console.timeEnd, it will print out the time between the when you called
console.time and when you called
console.table which can print out objects or arrays of values in a nice table format.
Overall, I am super glad to now know about being able to set a breakpoint for any time a DOM element changes. I am guessing it will come in handy more and more in the future, now that I know it exists.
Ready for day 10!