Knowing to log data to your DevTools console is one of the essential debugging skills when it comes to javaScript. I realised that there are many convenient and efficient ways of doing this and would like to share with the community.
Contents
Printing messages 🖨
We might be familiar with the most basic console.log() and console.info() that prints the value of the variable/message to the console.
Adding a message along with variable is useful and helps identify the value being printed. Moreover, this could be customised to a great extent.
- Enclosing the variable in {} avoids the necessity to add a text as the variable name is printed beside the value by default.
2. When there is a lot of information being printed on the console it is difficult to make the required message stand out(you know the pain if you are using redux-saga with redux-logger that logs information with every action), to resolve this we can custom style our messages.
3. We can further improve our debugging experience by using console.warn() that prints messages in yellow background and console.error() that prints messages in red background.
4. We can filter the logs based on the type of console we use from the Default levels dropdown.
Trace 🎯
It is a very common practice to write a reusable function and use it at multiple places. I have ended up not knowing which one is calling which and spent hours debugging. Well, we now have console.trace() to save us. This has been a life-saver!
Assert
Evaluating conditional operators is yet another debugging that needs to be done often. We can avoid writing ternary or if-else statements with console.assert()
Performance ⏱
We have a couple of options to measure performance.
- I use console.count() to check the number of times a method is called. In react, I use it to check the number of times my component re-renders on state changes.
2. Use console.time() to calculate the time taken for your program to execute and for page load. I prefer using the Performance tab of DevTools for measuring page’s performance.
Groups & Table
I, personally, don’t use these often, but you can check Console API Reference for details. In fact, all the above were referred from the official docs.
That’s all Folks !!!
Do let us know in the comments the lesser-known ways of console logging that you use.