Block Scope
Description
Anonymous functions can be used to mimic block scoping.
The basic syntax of an anonymous function used as a block scope (or a private scope) is as follows:
(function(){
//block code here
})();
This syntax defines an anonymous function that is called immediately. This function is then called via the second set of parentheses at the end.
Example
These private scopes can be used anywhere variables are needed temporarily, as in this example:
function outputNumbers(count){
(function () {
for (var i=0; i < count; i++){
console.log(i);
}
})();
//console.log(i); //causes an error
}
In the code above, a private scope is added outside the for loop.
Example 2
This technique is often used in the global scope to avoid naming collisions.
(function(){
var now = new Date();
if (now.getMonth() == 0 && now.getDate() == 1){
console.log("Happy new year!");
}
})();