Tuesday, December 14, 2010

Log to the built-in IE developer console

Rather than using JavaScript alert()'s to see the value of variables and alike, the IE developer tools allows you to output to IE's JavaScript console.
To open the IE developer tools, simply press F12

The console log command is simply:

So for example:

<script type="text/javascript">
    for (var i = 0; i < 5; i++) {
        console.log("hello" + i);

Would output something like this:

This is a rudimentary example, but s is especially useful if you want to know the value of many variables at a glance (rather than keep having to press OK for each alert()!)

Watch out for...

One gotcha is that your JavaScript will error in IE if your console is not open, because the console object will not be found, the simplest way around this is to remove your console commands after you have finished with them. I will post a workaround for this at a later date.

Of course using breakpoints and stepping through the debugging, is more often a better option (I'll do a quick post on how to do this at a later date), but in many situations outputting to the console is very useful.

The IE developer tool bar is built into Internet Explorer 7+ (I pressume it will also be in IE9+). As mentioned above you can access it by pressing F12 (or by using the menu).

More information

There are many variations of console.log, more information available on the MSDN site: Using Console for Logging Alerts and Error Messages

These posts are only here to give you quick and easy tips... however if web development is your day to day role, I'd highly recommend getting familiar with the built-in IE developer tools. More information is available on the MSDN site: IE Developer Tools tutorials

1 comment:

Unknown said...

HOw to do this on chrome ????????