This chapter is an extension of JS Scope and Memory block scope article.

Scope created for the variables due to blocks such as if, if-else, for, while, do-while is a block scope. Typically, in languages such as C++ and Java, variables defined inside block cannot be accessed from outside.  But JavaScript does not support this feature.. Variables defined inside a block can be accessed anywhere within the function. To avoid this,block scope can be mimicked by using self-executing anonymous functions

Syntax

(function(){

            //code here

})(); 

The syntax defines an anonymous function which can be used with the block statements. The ‘()’ at the end of the function indicates that function is self-invocating. In syntax (function()…) the ending and closing brackets enclosing function() is important because otherwise it becomes a function declaration and it cannot be followed by ‘()’ -  the self-invoking parentheses. These can be used where the variables are needed temporarily, as they get destroyed when the function is finished executing. It allows users to use variables without polluting global namespace.

Example of block-scope mimicking

 

›› go to examples ››