Using the console to debug JavaScript

The various console methods and how they can be used to your advantage
Published on Dec 19 2014 by Dougie Collins

If you’re a front end developer who deals with only HTML and CSS, getting into JavaScript can be a bit intimidating. With CSS figuring out exactly what was happening to any element on the page was relatively easy as most of the information provided to you within a glance. The declarative nature of CSS meant that web inspectors could easily visualise for you how each element is being styled.

Getting around JavaScript

Unfortunately JavaScript adds an extra layer of complexity with the majority of helpful tools aren’t so seemingly obvious at first glance. As in introductory we will cover displaying variables and messages to the front end and working with JavaScript in real time to see exactly what is availible to us.

Displaying information to the front end

alert() was probably the first JavaScript function you were taught and was a great way of showing information to a user. It was handy for testing as you could send information such as a variable to the front end as well as getting the message to appear when you wanted. Seems like everything you’d ever want! Below is a basic example of seeing testing what a variable’s value is via an alert().

var currentPage = window.location.href;
    alert("page address is: " + currentPage);

There are…less aggressive ways of display information when trying to figure out how the browser is interpreting JavaScript. This method does work but its rare you will only be testing one value at a time and becomes troublesome when viewing objects. The JavaScript console’s main advantage is displaying timely information in an interactive way, so lets look into using it!

Viewing the console

A modern browser inspector should come with a console. It can be access through the web inspector via the console tab (the last tab) as well as the pressing the ‘escape’ key when focused on the web inspector. The console gives you access to everything JavaScript has in that moment (keep in mind when adding breakpoints) and is useful for displaying messages, testing variables and interacting with JavaScript objects.

accessing the console

A console doesn’t look like much when first opened

console with elements

The console can also be accessed by pressing ‘escape’ when looking at DOM where I use it most

How to write to the console

To send a message to the console, write the following in your JavaScript console.log("message");, where the message can be a variable or any text (read: string) you’d like to output.

Log types

In most cases you will only need to use log, but the console always has warn and error methods. warn comes in handy when displaying non-crucial errors than may need to stand out from any other logs on the page, whereas error should be used to catch critical errors such as an ajax request not returning any data.

console.log("Notice: thank you for noticing this notice. Your noticing has been noted.");
console.warn("There were more more than 35 image requests on this page, it is affecting page load");
console.error("Nope");

log types

how the different types of console outputs appear

Using logs to test logic

Below is an example of a form validation than checks all the fields are valid and displays an error message if the validation fails. There are two logs to check the two functions are working as expected when the form is validated.

function validateFields() {

    var invalidFieldCount = $("form input.invalid").length;
    console.log(invalidFieldCount + " invalid fields.");

    if (invalidFieldCount) {
        displayErrorMessage();
    }

}

function displayErrorMessage() {
    console.log("creating error messages");

    // more code
}

validateFields() uses a log to display both the value of a variable and a message to the developer. For instance if all fields are valid the message would read “0 invalid fields” or, for example, ” 4 invalid fields”. If there are any invalid fields, displayErrorMessage() also has a log informing the developer that the function has been executed.

This type of writing to the console allows for quick skimming of executed functions and calculated values, almost as if reading comments in code. It comes in very handy when developing as you can place notes and basic information in clusters of functions without stopping anything on the front end. If you need to dig deeper into the order of execution or check when something hasn’t worked as expected, a quick look of your console logs can point you in the right direction.

validating fields

running the above example shows the diffidence in the logs when there are errors

Working in the console

As well as displaying information, the console can also be written to directly. You can type directly into the console to view what JavaScript has access to. It has a handy auto-complete and is fantastic for working with objects (JSON) as well as as listing DOM element.

Say you’re working on a tweet button to share the current page URL. The below should do the trick, with an added log just to see the full output of my tweet.

var link = window.href,
    tweetMessage = "I've written about " + document.title + ": ",
    tweet = tweetMessage + link;

console.log(tweet);

Looking at the log however, you’re greeted with I've written about Debugging Javascript: undefined. It seems the link didn’t work, so lets use the console to figure out why.

 working in the console

Typing window.location in the console returns an object which can be expand to reveal all properties and values. Sure enough expanding the object (via the arrow) shows the href value as well as some additional information. So now we can go back to my code link and update it to window.location.href and the problem is solved!

Conclusion

Working in the console directly can be great as sketchpad to confirm logic for any global scope objects. For something non-specific to a function you are writing, trying writing it in the console first to see the output.

For timely and specific things, its best to add a log in your JavaScript. Sending objects often leads to best results as you can expand them in the console to see any additional properties and values that may come in handy for your development.

So try using the console in the hopes that it makes a strong connection between the JavaScript you’re writing, what that JavaScript has access to and what the browser is doing with it. The console is my first reference when tracking down those pesky undefined is not a function error messages.

Header image taken by Trammell Hudson via http://commons.wikimedia.org/