Variables lifetime and scope



Variables begin their life with a declaration. The remainder of their life within the application depends on where the variables are declared.

To declare a variable in JavaScript, you use the var keyword. The following code demostrates how to declare variables and gives them a value:

<script type="text/javascript">
    //declaring variables
    var x, y, z; 
    
    //declaring variables and gives them a value
    var a =0.0, b=0.0, c=0.0 
<script>

After a variable is available for use, it’s considered to be “in scope”. The duration over which the variable remains in scope depends on where the variable is declared.

Global variable scope

A variable that has global scope is available throughout the webpage. The code below gives an example of global variable:

<body>
    <h2> Variable Scope - Global Variables </h2>
    <input type="submit" onclick="globalVar()" value="GLOBAL VARIABLE" /><br />
    <div id="#div1">   </div><br />
    <div id="#div2">   </div><br />
    <!--  GLOBAL VARIABLE -->
<script type="text/javascript">
    var globalVar = function () {
        var color = "Blue";
        if (color) {
            //this is a GLOBAL VARIABLE
            var color = "Purple";
            //this statement print Purple the value of color changed to purple
            document.getElementById("#div1").innerHTML = (color);
        }
           //this statement will print purple
    document.getElementById("#div2").innerHTML = (color);
    }
</script>
</body>

Local variable scope

A variable with local scope is available only within a specified context. When both the local and global variable have the same name, the local variable will take precedence over the global variable.

The code below gives an example of local variable:

<body>
    <h2> Variable Scope - Local Variables </h2>
    <input type="submit" onclick="localVar()" value="LOCAL VARIABLE" /><br />
    <div id="#div1">   </div><br />
    <div id="#div2">   </div><br />
         <!--  LOCAL VARIABLE -->
<script type="text/javascript">
    var localVar = function () {
        var color = "Blue";
        function printColor() {
            //this is a LOCAL VARIABLE - because is inside a function
            var color = "Purple";
            //this statement print Purple
            document.getElementById("#div1").innerHTML = (color);
        }
        printColor();
        //the following alert is outside the function and will print color="blue"
        //this statement will print blue
        document.getElementById("#div2").innerHTML = (color);
    }
    </script>
</body>

PROMOTIONS