Thursday, 23 May 2013

Variable scopes in JavaScript

Friends,

Recently I had a few technical discussions. After those talks I thought it would be better if I refresh my understandings on "scopes in JavaScript". I am sharing my lab work here.

Lets begin with an example.

   var scope='global';            // variable in global scope  
   function checkLocalScope(){  
      var scope = 'local';        // variable in local scope   
      console.log(scope);  
      checkLocalScopeAgain('localscope');  
      console.log(scope);  
   }  
   function checkLocalScopeAgain(scope) {  
      console.log(scope);        // variable in local scope        
      // this will only modify local variable and global is untouched  
      scope = 'testing';             
   }  
   function checkBlockLevelScope(){  
      if(true){  
        var scope='no-block; hence function scope';     // No block level scope   
      }  
      console.log(scope);        // Here variable has functional scope  
   }  
   function Constructor(){  
      this.scope = "instance";        // instance level scope  
   }  
   // prototype property is never get invoked as similar property is present in constructor  
   Constructor.prototype.scope='prototype attribute';    
   // but this will get invoked  
   Constructor.prototype.variablescope='prototype attribute';  
   function AnotherConstructor(){  
      this.scope = "instance1";        // instance level scope  
      return {scope:"object literal value"};  // I dunno how to name it. :)  
   }  
   var ScopeChain = function () {  
     var scope = "ROOT";        // Scope in closure chain  
     var root = "hello I am ROOT";  
     console.log(scope);  
     (function () {  
          var scope = "PARENT";  
        var parent = "hello I am PARENT";  
        console.log(scope);      
        (function () {  
          var scope = "CHILD";  
           console.log(scope);  
           console.log(parent); // finds the variable from scope chain   
           console.log(root);  // finds the variable from scope chain  
        }());  
     }());  
   }  
   console.log(scope);   
   checkLocalScope();  
   console.log(scope);          //To check whether global is modified   
   checkBlockLevelScope();  
   var c = new Constructor();  
   console.log(c.scope);  
   console.log(c.variablescope);  
   var a = new AnotherConstructor();  
   console.log(a.scope);  
   ScopeChain();  


The output to above code will be as follows.

   global   
   local   
   localscope   
   local   
   global   
   no-block; hence function scope   
   instance   
   prototype attribute   
   object literal value   
   ROOT   
   PARENT   
   CHILD   
   hello I am PARENT   
   hello I am ROOT   

I do not think there is anything left to explain as the output is self explanatory. I welcome all your comments.

No comments:

Post a Comment