Using anonymous functions to avoid global namespace pollution

I guess that you’ve written code like this in the past:

var user = document.getElementById("name");
var msg = "Hello, " + user.value;
alert(msg);

I can tell you that I’ve written several lines of code that resemble the previous snippet in the past. However, you should avoid it whenever possible. The main problem with it is that you’re polluting the global namespace and that is something you shouldn’t do.

In these cases, there’s really a simple strategy for avoiding this unneeded pollution: we can take advantage of anonymous functions! Here’s how I’d write the previous snippet:

(function() {
    var user = document.getElementById("name");
    var msg = "Hello, " + user.value;
    alert(msg);
})();

The syntax might seem awkward at first, but if you concentrate, you’ll see that it’s really simple. We define an anonymous function and execute it in place. (notice that the statement must end with the braces so that it is interpreted as a function invocation).

And that’s it for today. Keep tuned for more tips on JavaScript.

Advertisements

~ by Luis Abreu on August 27, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: