You have for sure used
The console can do much more than printing any string or variable you pass to it: it can also measure time, start some browsers built-in tools, help you trace bugs in the code, etc.. Let’s see some of those functions.
You have to start a timer with
console.time() passing a name as an input parameter. This will be the name of the timer. You can have up to 10.000 timers running simultaneously!
To stop the timer and print the elapsed time, use
console.timeEnd(), passing the name of the timer.
console.time('time doWhatever') .. doWhatever() .. console.timeEnd('time doWhatever')
You can also display the elapsed time without stopping the timer with
console.timeLog(), but this will only work in some modern versions of Firefox.
Trace your code
console.log() to trace an error is extremely inefficient. Ok, you are echoing the error, but, do you know how the code did get there? How was the function you are debugging executed? Which nother part of your code called this function?
For a better debugging experience, be sure to use
console.trace(). It will print not only the message you pass as a parameter, but also the whole trace until this
console.trace() was executed.
Style your console output
I am sure you already know this, but just in case, remember that you can style your output passing some CSS styles to console.log as a second parameter and the “%c” within your first parameter:
console.log(“%chere is the message”, “color: yellow; font-style: italic;“)
Using tables in the console
You can print your information as a table passing an array or an object to the command
The first column and row will be labeled with the index of the array or the property names of the object being printed. Some browsers may limit the number of rows.
Print an interactive list of the properties of an object
If you want to display a XML/HTML object, better use
console.dirxml(). This will output an interactive list of all the trees of the element.
For instance, if you use this on this website:
console.dirxml( document.getElementById(“page”) )
you will get this output:
Too many outputs?
Just clear all the content using console.clear()
Do you want more?
I have written here only the functions that I consider the most useful/interesting, but there are more. Please check the MDN web docs for more information about the console object.