Stop Using Alerts To Troubleshoot JavaScript

I didn’t think this was common practice to use alerts for debugging anymore until I talked to another web dev friend of mine – he was still using alerts to test and debug heavy JavaScript applications. For simple debugging this method might be useful, but the headache of trying to debug issues with complex objects would be unbearable.

There is a helpful JavaScript function:

console.log("this will show in the console");

You can log anything in JavaScript. Anything. Any object, any variable. All this can happen without stopping the window from loading and continuing doing its thing. That’s not even the most convenient part of it – if we pair this function with FireBug, when you log an object in the console, it will give you a full output of the object. Let’s take out test object as an example:

var ourObj = {
    options: {
        firstOption: true,
        secondOption: false
    init: function() {
        console.log('we started our object');
    doAction: function() {
        console.log('action started!');
    reverseAction: function() {
        console.log('oops! undo!!');
    runSomeAjax: function() {
        $.post('/path/to/page', {postVar: true, anotherVar: "text"}, function() {
            console.log('ran our ajax!');

If we run the following function:


In the console we’ll see the following output:

Object { options={...},  init=function(),  doAction=function(),  more...}

Sure, that’s nice, but if we dig a little deeper into the DOM output by clicking on it, we get:

options: Object { firstOption=true,  sectionOption=false}
    firstOption: true
    secondOption: false
doAction: function()
init: function()
reverseAction: function()
runSomeAjax: function()

That doesn’t look like much with such a simple object, but you can imagine how useful this could be with larger, more complex objects. In the case of objects that have event handlers attached to them, this becomes even more useful. If you log a jQuery element object, it gives you an entire breakdown of the element and its children – something that a simple alert wouldn’t be able to provide you. I highly suggest if you haven’t played around with console.log(), that you give it a go and you’ll undoubtedly realize its potential.

View Comments
There are currently no comments.