Tuesday 26 July 2011

Debugging JavaScript using Firebug console

Sometimes the fastest way to find bugs is just to dump as much information to the console as you can. Firebug gives you a set of powerful logging functions that you can call from your own web pages.

console.log

The easiest way to write to the Firebug console looks like this: console.log("hello world")

You can pass as many arguments as you want and they will be joined together in a row, like console.log(2,4,6,8,"foo",bar).

Logging object hyperlinks

console.log and its related functions can do a lot more than just write text to the console. You can pass any kind of object to console.log and it will be displayed as a hyperlink. Elements, functions, arrays, plain ol' objects, you name it. Clicking these links will inspect the object in whatever tab is most appropriate.

String formatting

console.log can format strings in the great tradition of printf. For example, you can write console.log("%s is %d years old.", "Bob", 42).

Color coding

In addition to console.log, there are several other functions you can call to print messages with a colorful visual and semantic distinction. These include console.debug, console.info, console.warn, and console.error.

console.log() and older browsers



You can write a script which creates console functions if they don't exist. For example following script can be used to alert the given value when console.log() is unavailable.


<script type="text/javascript">

if (!window.console) console = {};
console.log = console.log || function(s){alert(s)};

console.log('testing')

</script>



Click here to read more

No comments:

Post a Comment