Deutsche Startseite · English Homepage

STRAVID - Building software collectively.

Stop the Javascript alert() madness

We have the year 2010 and there are still people out there using alert() to debug javascript code.

function doSomeMagic(argument) {
    alert('doSomeMagic argument: ' + argument);
// do the magic stuff

return argument;

}

This is madness! In times of Web Inspector and Firebug it’s pure masochistic to use an alert() for this kind of stuff. What, still not convinced? Here are some arguments against alert():

Convinced programmers let me show you a more convenient way of doing this! First of all you have to use a proper browser, with both Chrome and Safari you are good to go. In Firefox you have to install the Firebug extension or wait until they have a native Javascript console.

Now you can use the console object to your advantage, with the log method you can write your debug messages to the console.

function doSomeMagic(argument) {
    console.log('doSomeMagic argument: ' + argument);
// do the magic stuff

return argument;

}

To access the console in Chrome and Safari you right click in the page and select the menu point "Inspect Element". In the new window you click in the left bottom corner the console button.

In Firefox you open up Firebug and switch to the console tab to view your logged messages.

A very sweet feature is the so called object hyperlink, if you log a object with the console it will generate an object hyperlink in the console output. You can click on it to get a nice formatted look at the object and all its attributes and values.

var myObject = {
    info: 'Some random object',
    weight: 42,
    trackingList: [21, 13, 7]
};

// will create a object hyperlink
console.log(myObject);

console offers many more handy methods to inspect and control your Javascript code so give it a chance and check it out!


You have questions, ideas or feedback? I like to hear from you and I'm looking forward to exhange thoughts. Please send an email to david@strauss.io and say “Hello”.

Random Page
Sitemap
Imprint
Privacy Policy