Warn and error logging
To add extra zest to your logging, you can use console.warn() and console.error() to change the output color of your message (it works in most browsers to show a red or yellow background!)
Ever wanted to see how fast or slow a function evaluates in? Well, you could use some hacky things where you create some date variables at the beginning and end of a function, but there are NEW ways of doing things.
Introducing..... console.time() and console.timeEnd()! Using these two functions, you can evaluate and output the duration of a method automatically.
Also, if you want to add extra/multiple time functions inside of one method, you can use console.time(label) and console.timeEnd(label) which will let you nest timings as long as the labels are unique.
Asserting with console.assert()
console.assert(<expected true value>, <error message here>)
Asserting with the console is one of the coolest things you can do. If you normally write outputs of variables to see if they evaluate to something, “console.log(x == 1)”, you can refactor that into a really nice output using assertions. With assertions, instead of printing when the value is true, it’ll only return if it is false, and you can even return a fancy output!
console.assert(true == false, “True does not equal false!”) will output “True does not equal false!” but if you change it to
console.assert(true == true, “True does not equal true!”) will return nothing as the statement is true.
Grouping can be useful in some situations. If you want to keep track of a ton of different functions, you can use console groupings instead of function pretends (e.g. you don’t need to say “functionName: <output>”). You can even collapse certain groups to clean up your output :)
console.group(name) creates a group, and
console.groupEnd(name) finalizes and outputs the group. Pretty neat stuff!
Supercharging console.log() is a crucial step in creating beautiful outputs of logs, so I hope you learned something helpful in this article. If you learned something, please let me know by tweeting me, @kvizdos!