I was answering some coding questions on Free Code Camp forums and noticed that in all the questions, people where just logging the variables like this:
console.log(myVariableX)
... ( a few more lines in between)
console.log(theOtherVariable)
This resulted in the logs like this:
23.45
98
This does not help with figuring out what is happening. Specially if you are somebody who has jumped in to help quickly.
Always add a message to your console.logs!
console.log can accept multiple strings:
console.log('myVariableX:', myVariableX)
... ( a few more lines in between)
console.log('theOtherVariable:', theOtherVariable)
This will result in logs like this:
myVariableX: 23.45
theOtherVariable: 98
This is a simple tip, but I've seen it help people so many times.
When I'm coding, I use some weird names to spot them quickly in the logs, to be able to tell them from serious logs right away:
console.log('myVariableX the UnicornFOO:', myVariableX)
Now I can quickly spot UnicornFOO or search for it in the logs.
I hope this helps you with debugging!
Photo @sigmund, unsplash
Top comments (5)
You can also have some sort of a label inside your
console.log()
in order to be able to filter these logs. It comes in very handy if in the console there are many other logs from 3rd party tools or your framework.I don't use console.log directly, I use the debbugger of devtools, if I have to log something, does through an abtraction.
I have a rule in eslint that does not allow me to use console.log.
Why comprehend using the debug for bigger logical bugs but for smalk fixes console.log is just more conveniet
There are several reasons, one of them is that the console log casts the data, forces the data to convert to another type to be able to display them on the screen, all the data is converted to a primitive String.
Another reason is that people often forget to remove the console.logs in various parts of their code.
Just open a debug tab on a web page and see how people forget to remove console.log in production.
Using console.log could be considered an anti-pattern that can turn into a big ball of mud.
Third reason it is very easy to use a debbuger nowadays.
There are many articles that talk about this topic.
Thanks for your detailed answer. But some points: