Javascript function and variable scope

Scope of a Javascript variable?

What is scope?

  • The scope is the region of your program where a variable is defined.
  • Function parameters and variables defined with "var" keyword inside the function are only available inside the function and for that reason live in a local scope.
  • Any other defined variables are available in a global scope, which will be the same as the web-page.
  • Any variables defined inside a function without the "var" keyword will exists in a global scope.
  • Any local scope defined variable has access to any global scope defined variable.
  • Any global scope defined variable has NO access to any local scope defined variable.
    Example:
    <script type="text/javascript" defer>
      var myVar = "global<br>";           // Declare a global variable
      function showScope( ) {
        var myVar = "local ";             // Declare a local variable
        document.write(myVar);            // Uses the local variable
        anyVar = "Implicitly global<br>"; // This implicitly declares a
                                          // new global variable
        document.write(anyVar);           // Uses the new global variable
      }
      // calling the showScope function
      showScope();                        // prints "local Implicitly global"
      document.write(myVar);              // prints "global"
      document.write(anyVar);             // prints "Implicitly global"
    </script> 

What is scope chain?

  • Functions can contain other functions that can contain other functions and so on and they all have their own local scope nested inside their parent scope. This is known as a scope chain.
  • The container function cannot access variable defined in functions it contain (nested local scope), but those functions can access it's container variables.
    Example:
    <script type="text/javascript" defer>
      function showScope( ) {
        var myVar = "local, ";         // Declare a local variable
        function nestedFunc() {        // Function, nestedFunc, is local to showScope
          var nestVar="nested local, " // Declare a (nested)local variable
          document.write(myVar);       // Uses the container local variable
          document.write(nestVar);     // Uses the (nested)local local variable
        }
        document.write(myVar);         // Uses the local variable
        nestedFunc();
     //   document.write(nestVar);     // This will cause an exception
      }
      // calling the showScope function
      showScope();                     // prints "local, local, nested local, "
    </script>

What is lexical scope?

  • Functions have lexical scope in Javascript. This means that the scope of a function is created when it is defined, not when it is executed (runtime).
    Example:
    <script type="text/javascript">
      function calculateArea(){  return width*height; }
      function getVolume(length){
        var width = 9, height = 2;
        return length*calculateArea();
      }
      /* One might think that calculateArea () has access to the width and height
         variables when it is executed inside the getVolume (). This is not the
         case as both function are define in the global scope.  */
      /* To get it to what we want, we can rewrite this to: */
      function getVol(length){
        var width = 9, height = 2;
        function calcArea(){  return width*height; }
        return length*calcArea();
      }
      alert(getVol(4));
     // alert(getVolume(4)); // will not work
    </script>

What is NOT a local scope.

  • Any block of code surrounded with the {} symbols define NOT a local scope, as in many other languages.
    Example:
    <script type="text/javascript" defer>
      function TestScope( ) {
        var i = 0;                       // i is local to the function
        while (i<2) {
            var x = 0;                   // x is also local to the function
            for (var y=0; y < 5; y++) {  // y is also local to the function
                document.write(y+", ");
            }
            document.write(y+", <br>");  // y is still defined and prints 5,
          i++;
        }
        document.write(x+", ");          // x is still defined and prints 0,
      }
      TestScope();
      // prints
      //  0, 1, 2, 3, 4, 5,
      //  0, 1, 2, 3, 4, 5,
      //  0,
    </script>


© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.