The JavaScript console object has many methods and tricks. Here are five worth knowing about.
As someone who maintains the front-end, it's important to learn how to use console.log. This method can let you show information on the screen on console when debugging certain issues.
But do you know any other secrets about the console object?
In this article I will summarise 5 tips for using the console object. It's my hope that these are helpful.
1️⃣ console.log()
Basic usage skills
console.log() is one of the most commonly used methods in JavaScript and can be found nearly anywhere.
But when there's too much information, it becomes hard to know what any of it means!
So, is there any good way to see more clearly what it is?
Yes, we just need wrapping the output in an object.
CSS style
It's amazing that console.log can also be customized!
2️⃣ console.warn()
When the console prints out all of this information, it can be difficult to find what we want. Don’t worry, console.warn can help us because it has a special yellow colour flag.
3️⃣ console.error()
We routinely send HTTP messages to request data and when an error occurs in the request, I like to print an error message via console.log.
But… that’s not a good idea, instead, we should use console.error!
Why? Because it not only has a unique red error flag but also prints the stacked relationship of function calls.
4️⃣ console.time() & console.timeEnd()
And what if you want to know the execution time of a piece of code? Probably you have done something like this:
But thanks to the console functions, we have a better option:
And what if you want to count the execution time of multiple pieces of code? No worries, that is something we can also easily do, just like this:
5️⃣ console.table()
As we saw previously, we often use console.log (and the other functions) to print some information but sometimes that is not intuitive (just check the following image):
Luckily, we have another function called table():
Much better, isn’t it?
🌎 Let’s Connect
- Twitter: @thenaubit