LA.NET [EN]

Aug 27

Using anonymous functions to avoid global namespace pollution

Posted in Javascript      Comments Off on 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.