Debugging JavaScript Behind the Scenes

Learn how to keep your page layouts clean from debugging mess using the browser’s console API.

Meet the Console

Our final post for 2010 comes after a few discussions with industry friends. I was surprised to find that a number of them had never used the in-browser debugging consoles for JavaScript. Regrettably this also included a certain member of our own office, but he can remain nameless for now.

So for those of you who haven’t yet been formally introduced to the browser console API, here’s a great way to start fresh in 2011.

Visual Debugging

When you work on websites, debugging is mostly a visual experience. It’s easy to see misaligned columns or overlapping text, change something, and then refresh. With PHP, error reporting stops the script and displays the issue right on the page. In short, a good chunk of web design errors can be handled identified by page load.

The console API is a browser object that can be used to output debugging information as a page loads. For example, the console might output an error if an image element had a source of “definitelynotareallink” instead of a valid URL. The console really shines when it comes to JavaScript, especially when sorting through the DOM.

Chrome Developer Tools Panel

Firebug has the best documented (and robust) console API, but Firefox isn’t the only browser that can use it. Most modern browsers have development tools that include a console tab. For Chrome and Safari, you can reach this view by right-clicking and selecting “Inspect Element” from the context menu.

Simple Examples

The console support a number of options, but you’ll probably only use the same 3-4 regularly. From my own experience, the log() function is by far the most useful. It outputs a new message line to the console that can contain plaintext, DOM Elements, or variables. The examples below cover a couple of the more common functions.

In this script, the console outputs a different result depending on whether or not the full_name variable is empty:

For this jQuery click event, the console will return information about the target element’s attributes:

I’ve put together a demo page to help showcase more of the basics. Try running it with your console open, and view the source for specific explanations.

Console API Demos

Direct Input is Allowed

The console goes much deeper than simple outputs, and can also accept direct input similar to a command line. For example, type “document” and press enter to get the page returned. Console DOM traversal is a bit heavier (and not as immediately useful) for an introduction, so we’ll leave that for another post.

Keep the Page Clean

Debugging behind the scenes keeps your page clear of any “testing only” outputs that must be deleted before launching. It’s entirely possible to leave console debugging in a live installation without the user ever noticing.

Next time you’re working on a JavaScript project, give the console a go. It’s a hell of a lot easier than creating random alert() boxes for specific triggers. When it comes to troubleshooting, unobtrusive is wonderful.

If there’s a further interest in this topic, there are a number of things we can do more on, particularly with tracking jQuery events. If you have any suggestions, questions, or expertise of your own to throw in, leave a comment below and we’ll compile something for a future post.

Links & Reading

  1. Firebug and Logging
  2. Apple’s Documentation on Console Debugging

Posted Friday, December 31st, 2010 · Back to Top

SPONSOR

Add Comment

28 Comments 5 Mentions

  1. Niamor Author Editor

    You cannot leave console calls in your scripts. It really unobstrusive with webkit based browsers but for others, specialy for IE, but also FF without FireBug installed, your js would crash…

    ·

    • Gerald Fullam Author Editor

      I confirm. Watch out for this — I have spent hours “debugging” scripts that weren’t working in the live environment only to realize that my console calls were causing the problems. Even with Firebug installed, the console calls will crash your script if the console is not active. Remove them before you go live!

      ·

    • Matthew Author Editor

      Although it is best to remove console calls, one way to avoid errors is to use the short-circuit operator, &&:

      window.console && console.log(“This won’t execute if the console is not active.”);

      ·

  2. Ivan Nikolić Author Editor

    As Niamor said, if you don’t have some kind of console mechanism inside browser, that browser will stop with code execution if it encounters console statements.

    One way to fix that is to use Firebug Lite’s console detection: http://is.gd/jT5N5

    ·

  3. Romain Bessuges Author Editor

    For the two comments above : a simple if(window.console) will do the trick and won’t stop the code on IE.

    I wanted to add that this tool can become very handy for flash developpers who can use ExternalInterface to call the console’s methods.

    A simple embedded JS with root level functions (consoleInfo, consoleLog, consoleError, etc.) can be called directly by, for example, a static AS3 class named Console, implementing the same methods.

    ·

    • Tony Stuck Author Editor

      I typically place this at the top of my JS so I don’t have to worry about adding a million if statements to my code:

      if(typeof window.console === 'undefined'){var console={log: function(e){/* alert(e) */}}}

      It can also come in very handy with IE debugging, as you only have to uncomment one piece to get alert statements for all of your logs..

      ·

      • Zach Dunn Author Editor

        Thanks for that Tony, seems like the most elegant solution to getting this working across the board.

        ·

      • Josh Ellington Author Editor

        Or you could just use this nice function to enable cross-browser logging:

        // usage: log(‘inside coolFunc’,this,arguments);
        // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
        window.log = function(){
        log.history = log.history || []; // store logs to an array for reference
        log.history.push(arguments);
        if(this.console){
        console.log( Array.prototype.slice.call(arguments) );
        }
        };

        ·

  4. Romain Bessuges Author Editor

    Oh and very nice article and illustration, by the way !

    ·

  5. Kresimir Katusic Author Editor

    Thx for console tips, I didn’t know about console.dir() it’s fast way to look properties and attributes of elements.

    ·

  6. Greg Author Editor

    While I agree that using an if statement to check for the console would work, it’s a bit ungainly.

    I imagine most IDEs will let you run some sort of regex to find console.foo lines and delete them. As a non-regex-wizard, I usually just manually delete those lines. Which, honestly, you SHOULD be doing prior to production anyhow.

    ·

  7. damjan Author Editor

    Nice article, it’s also possible to hot-patch the code and add log statements ‘on the fly’ using conditional breakpoints – check http://samuraiprinciple.com/2011/01/03/adding-log-statements-without-reloading-the-page/

    Cheers and happy New 2011

    ·

  8. Matthew Author Editor

    I have to quibble with your contention that Firebug has the best documented and robust console. The Chrome Developer Tools are very well documented, and they make specific mention that Chrome implements the entire Firebug API (http://code.google.com/chrome/devtools/docs/console.html). For any documentation missing from code.google.com, developers are instructed to reference Firebug’s site.

    Also, on Windows machines, you may use Ctrl+Shift+I to reach the console, and if you are in any specific tab of the developer tools, you can toggle the console on and off by hitting Esc.

    ·

    • Greg Author Editor

      The Chrome tools are great. I do not like the live editing of CSS, though… I’m used to tabbing, seeing changes go live as I type them, and hitting either tab or enter to continue on. Also small things like right-clicking to get a new rule/property fired up instead of double-clicking. In general, navigating around the “Styles” view in Chrome needs refinement. There are no patents; not sure why they don’t just rip off Firebug’s navigation wholesale.

      ·

  9. Eduardo Dx Author Editor

    The in-bwoser console is a pretty handy tool.
    I wish Firefox could catch up with the other browsers, because I miss Firebug a bit.
    While that doesn’t happen I go working with the, gorgeous, Chrome Console.
    Nice article!

    ·

  10. Paul M. Watson Author Editor

    console.log is great but as others mention make sure you have a catcher for browsers with no firebug/console object. I usually wrap this in a Rails if dev mode statement for Internet Explorer which alerts the console.log text (though be careful you don’t do it in a big loop or you’ll be closing lots of alerts.) Do it properly though as you can also get “redeclaration of var console” errors.

    ·

  11. Montreal Web Design Author Editor

    New version is firebug is even better. Check “Whats’ new in Firebug 1.6″ (http://blogs.sitepoint.com/2010/12/01/whats-new-firebug-16/)

    ·

  12. orionrush Author Editor

    oh please oh please – more debugging tips for jquery! +1

    ·

  13. ParituS Author Editor

    Thank you, so I need it for work.

    ·

  14. Christian Vermeulen Author Editor

    Paul Irish came up with a pretty good solution to leave your debugging calls n your script. If you check whether there actually is a console before writing to it your javascript will not crash in a browser like IE.

    On his website he posted a neat class which you can put on top of your script:
    http://benalman.com/projects/javascript-debug-console-log/

    ·

  15. Christian Vermeulen Author Editor

    Oops, it’s actually Ben Alman who came up with it, but he credits Paul Irish for a lot of help ;-) My bad!

    ·

  16. Atticus White Author Editor

    Yesss, I don’t think in the past few months I’ve developed a site without my developer tab open.

    Console is better than alert box in so many ways. Not only is it less annoying by the 50th page refresh, but you can also load objects into the console and view the JSON tree.

    Network tab will be extremely useful for anyone playing with AJAX requests. you can view all your post headers, the response as a JSON object, time of execution, all without doing any console.logs.

    Also, curious how other sites are dynamically updating content on the fly without page refreshes? Check out their network tab and see what their server is returning. I’ve reconstructed my approach to a few methods of delivering content to my front end via AJAX by inspecting sites like Facebook, Twitter, etc.. watch how other sites pass data to their front end via Network tool sometime, you may learn pick up a couple new practices.

    ·

  17. طراحی سایت و سئو Author Editor

    Oh and very nice article tnx

    ·

  18. Cherry Picker For Sale Author Editor

    yay for debugging!

    ·

  19. بهینه سازی سایت Author Editor

    relay help me tnx

    ·

  20. ترجمه انگلیسی Author Editor

    thanks i am worldtranslators

    ·

  21. Paul D. Mitchell Author Editor

    Using Google Chrome, Right Click on an item which is changing ‘visually’ when the action you want to debug takes place, and click ‘Inspect Element’. In this case we can inspect the temperature value. Right Click again on the element from the DOM view and select Break on -> Attributes modifications. Now perform the action you want to debug.

    Affordable web designers USA

    ·

  22. CaesarTSUI Author Editor

    不明白是干什么用的。

    ·

 

Build Internet by One Mighty Roar. Since 2008.