Debugging JavaScript: Logging

If your JavaScript  executes but not how you expect it to, one method to find out what is going on is to add code to the script that outputs information to the console as the script executes.

Vanilla Logging

The method that most JavaScript developers default to is to use console.log similar to the screen shot below.


Opening the Chrome DevTools (F12) displays the output for this script as:


It doesn’t take many messages to appear before I reach information overload so I use this method sparingly. To assist in such situations the JavaScript Console object has other methods that can be used to help make categories of logging easy to see., Console.warn() and Console.error()

In order to differentiate between different classes of logging, you can use the .info, .warn and .error methods of the Console object.

Here is the function updated to use these methods, note that the call to each of these are the same as console.log


And the output from the Chrome DevTools console is:


This output comes from Chrome 67 and note that the first two messages which although use .info() the output is identical to .log(). Unfortunately since Chrome 58 info() and log() are shown identical in the console window. (If you would like to know more this link is a good place to start. The calls to warn and error are shown in red and yellow respectively.

Logging Groups

When reviewing the output from a related set of instructions such as the output from a function, it may help to keep the related information together. can be used to help in these situations.

The console output from this function shows, first collapsed:


and then expanded:



Another aid to improve readability, particularly when dealing with a lot of tabular data is to format it into a table using console.table. In example shown, an object is populated with data and then a call is made to console.table passing it the columboEpisodes object.


The output from the Chrome DevTools console is:



The very best method of aiding readability is to only have a message appear in the console if it breaks the expected condition at that point in the script. Console.assert can be used in such circumstances. If the assertion returns true nothing is shown. This can help reduce the noise of what is shown in the console window.


The output of the script is shown below, note that only one message is shown, the one returns false which is the second one, X is not greater than Y.



Javascript & JQUERY Book by Jon Duckett

The MSDN pages on the Console Object

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.