Skip to content

Scope chain in JavaScript | Code

  • by

The JavaScript scope chain is simply the locations where identifiers are declared that are searched to resolve the value of an identifier.

JavaScript resolves identifiers within a particular context by traversing up the scope chain, moving from locally to globally.

Scope chain in JavaScript

Simple example code of self executed function with Scope chain.

<!DOCTYPE html>
<html>
<body>
  <script>    
    var currentScope = 0; // global scope
    (function () {
      var currentScope = 1, one = 'scope1 ';
      console.log(currentScope);

      (function () {
        var currentScope = 2, two = 'scope2 ';
        console.log(currentScope);

        (function () {
          var currentScope = 3, three = 'scope3 ';
          console.log(currentScope);

      console.log(one + two + three); // climb up the scope chain to get one and two
    }());
      }());
    }());
  </script>  

</body>
</html>

Output:

Scope chain in JavaScript

Each function defined has its own nested scope, and any function defined within another function has a local scope which is linked to the outer function — this link is called the chain.

function parent() {    var name = 'Aastha';
    console.log(name); 
    //  Reference error: age is not defined
    console.log(age); 
    //  Reference error: places is not defined
    console.log(places); 
  
    function child() { 
    // function linked to parent() thats why name is accessible.
    
        var age = 23;
        console.log(name);  
        console.log(age);
        //  Reference error: places is not defined
        console.log(places);         function grandchild() { 
        // this function is linked to child() & parent() thats why name, age are  accessible.                var places = 'Coding';
                console.log(name);
                console.log(age);
                console.log(places);
        }
        grandchild();
    }
    child();
}parent();

Do comment if you have any doubt or suggestions on this JS scope topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.