www.netsi.dk

"The internet is just a layer on the real world" (don't forget that!)

Some tips for javascript console debugging

If you use a modern browser you have access to a log from your javascript code. You can log usefull information like status, events and errors to the log during development and sometimes on live soloutions. Many people know about this through development tools like Firebug for Firefox, Chrome developer tools and even Microsoft developer toolbar.

Opening the developer toolbar – F12

Often (at least on windows) you can press F12 key to activate the build in developer tools. When you do so you will get an extra panel, often at the bottom of the window.

The Chrome developer toolbar

The Chrome developer toolbar

Firebug for firefox

Firebug for firefox

Microsoft Internet Explorer 9 developer toolbar

Microsoft Internet Explorer 9 developer toolbar

If you open a developer toolbar you will normally get some tabs offering various areas of interest during your debugging of the content (be it javascript, css or other types). Here in this short post I focus on the Console part of a developer toolbar.

How to add logging in a safe manner?

You may run into browsers which simply don’t have a developer toolbar, so before you start logging away from your javascript code you should test if the current supports logging. The simple example of how to do that could be:


if (typeof console!==’undefined’) {

  console.log(‘hello debuggers!’);

};

This is a safe way which will not break if the page is viewed in an old browser. I will not go into optimizing this test, but of cause you should handle it in a correct manner.

What you also saw here was the basic method of the console object: the log method. Most people stop here: Use the

console.log('I am logging'+someVar);

and never get any further, cause it does what the (think) they need! But hey:

You do not need to build the output using string concatenation! You can simply use comma, as console accepts any number of parameters.

console.log(‘I can accept’,’ any ‘, ‘number’, ‘of ‘, ‘parameters!’);

console can more that “.log()”

Actually console also has some other pretty cool methods:

console.dir(object) will give you a chance to click your way through the “object”, like a tree view! Pretty handy for complex objects. You may also get it in XML – console.dirxml(object).

I will div no more into this subject, bug hey – Google is your friend and what is more, here is a list to take you deeper into the world of website debugging Smile

Links – relevant information
Video

Paul Irish: Become a Javascript Console Power-User

Share
Category: Code, How-to, Javascript
US

Your email address will not be published.