What is the difference between the following two blocks?
// block 1
{
console.log("anonymous block");
}
// block 2
(function anon() {
console.log("anonymous block 2");
})();
I ran this in Netbeans (using the node.js plugin) and they both seem to work…
The difference is that you can use the latter form to hide global variables without destroying them.
For example, suppose you’re using the jQuery library, which by default aliases its main namespace to
$. If you wanted to use$for a different purpose without changing how$is normally used, you could do something like this:In fact, it’s also useful for one other purpose. Since
undefinedis NOT a reserved word in JavaScript, it can be given a value and lose its purpose. So you could simply not pass a value into anundefinedparameter, and you know it will behave properly without clashing with a global value.