First of all, what is console.log?
“Console” is an object that provides access to the browser debugging console, and you can print values of your variables. You can use any kind of variables: string, number, boolean, object and array.
Here we have some examples with different types of results:
But “.log” is just one method of the “console” object and now we are going to see other useful methods.
Method .dir() print an object like an alphabetically ordered list:
Method error() print errors in the browser console. These errors are very visual because they are highlighted in red with a cross icon:
warn() method is very useful to test code too and specially, it is often used to throw warnings. This message in the console browser is highlighted in yellow.
console.table() print an object like a table, for better readability:
5. TIME and TIMEEND
Methods time() and timeEnd() are used together. They count the time a function is executing. Both methods take a string as a parameter and, of course, as they are counting the time for the same function, they have to have the same parameter.
When you have functions inside functions it’s very easy to get lost. But with console.trace() you can follow the trace of a function:
count() method counts the number of times it has been called. You can add an argument inside, and then, you can count all the times it has called with this argument. The argument is optional.
8. GROUP and GROUPEND
These methods work together, and accept a string value in their argument and has to be the same argument to both, like time() and timeEnd(). These methods create a block in the browser console where you can add more console methods. With this functionality you can separate results and have all organized:
When you have some messages in the browser console it’s a mess to find out about something. For these moments, we have “console.clear()” and console messages will disappear and “Console was cleared” message appears.
To end, I want to share with you a functionality that I learned a few weeks ago: put style in your console log messages!! It’s very easy: you have to add 2 arguments into “console.log”: first argument has to start with string “%c” and the second has the styles. You can add variables too.
Here you have an example:
And that’s all folks! I hope you find this article interesting and learn something new.