Join the DZone community and get the full member experience.Join For Free
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. Okay, you are echoing the error, but, do you know how the code got there? How was the function you are debugging executed? Which other 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
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
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.
Published at DZone with permission of Antonio Sanchez . See the original article here.
Opinions expressed by DZone contributors are their own.