Monday, April 13, 2009

Javascript Puzzler

Invoking an anonymous JavaScript function is a handy technique for avoiding namespace collisions in JavaScript code. The following two code snippets show the definition of a top level function followed by the invocation of an anonymous function. One of them, however, has a (easily fixed) problem (at least on Firefox 3.0.8). Can you spot what it is? Try figuring it out without running the code - don't cheat! Put your answer in the comments.

Snippet one:

function say(text) {
alert(text);
}
(function() {
var foo = "bar";
})();
view raw gistfile1.js hosted with ❤ by GitHub


Snippet two:

var say = function(text) {
alert(text);
}
(function() {
var foo = "bar";
})();
view raw gistfile1.js hosted with ❤ by GitHub


Surprising behavior. I'd be interested to find out if different browsers / JavaScript engines treat these code snippets in the same way.