Javascript Variable Scope

When we are learning the programming language, each language has its own variable scope.  In the Javascript, both function and object are also variables.  We can declare a variable in many locations inside, outside the function and object. Based on the location of variable it has the scope.

By the scope, we mean the lifetime of a variable i.e where the variable is visible and available for us to use in our code. In JavaScript, we have not many but just a couple of different types of scopes. In the Javascript we have

  1. Local Variable
  2. Global Variable

ES6 has introduce two new keywords for declaring variables,

  1. let
  2. const

The scope of variables declared using var is within the function it is defined and global if it is not defined inside any function, while the scope of let is restricted to within the enclosing block it was declared in and global if it is not defined inside any enclosing block.

Const keyword :
The working of const is the same as that of let, except that variables declared using const cannot be changed (reassigned). Hence, const is used for constants. However, an entire constant cannot be reassigned but their properties can be changed. For example:

const a = 5;
// this will not work
a = 7; 
const b = {
	a: 1,
	b: 2
};
 // this will not work
 
b = { a: 2, b: 2 };

// this will work since only a property of b is changed
b.a = 2; 

Local variable: When a variable is declared inside the function it has local scope. The local variable only visible and accessed within the function where it was declared. The local variable dies when function finished its task.

Global Variable: When the variable is declared outside of the function it becomes global variable and can be accessed from anywhere in the code.

The Javascript does not implement block scoping. We can achieve block with help of let keyword. In the example here we can access variable i and inFor outside the for loop block.

function scopeTest() {
   for (var i = 0; i <= 5; i++){
     inFor = i; 
   }
  console.log("Value of inFor" +inFor);  
  console.log("Value of i" +i);
}

The output of above code inFor as 5 and i as 6.  In the new version of Javascript allow us to use new keyword called let to achieve block level in the loop. Variables declared with let inside a block scope are only accessible inside that scope. If we use let to declare the i variable in a for loop, that variable will only be available inside the for a loop.

function scopeTest() {
   for (let i = 0; i <= 5; i++){
        inFor = i; 
   }
   console.log("Value of inFor" +inFor);  
   console.log("Value of i" +i);
}

For above code output value of inFor is 5 and we can’t access the i value outside so it will generate output message as Uncaught ReferenceError: i is not defined.

Static Variable scoping:
Here we are learning static variable scope in Javascript with D3 library.  Add the following code in our filename.js file.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title>Functional Javascript</title>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <script type="text/javascript" src="node_modules/d3/build/d3.js"></script>
</head>

<body>

<script type="text/javascript">
    function simpleFunObject(spec) {
        var instance = {}; 
        var headline, description; 

        instance.render = function () {
            var div = d3.select('body').append("div");

            div.append("h3").text(headline); 

//Adding box class and color to parent div 
            div.attr("class", "box") 
               .attr("style", "color:" + spec.color) 
               .append("p")
                   .text(description); 

            return instance; 
        };

        instance.headline = function (h) {
            if (!arguments.length) return headline; 
            headline = h;
            return instance; 
        };

        instance.description = function (d) {
            if (!arguments.length) return description;
            description = d;
            return instance;
        };

        return instance; 
    }

    var testScope = simpleFunObject({color: "#718024"})
            .headline("Javascirpt static variable scope")
            .description("This is a example of simple functional object in javascript.");
    testScope.render();
</script>

</body>
</html>

In above code, all three variable instance, headline, description are private variable belongs to the simplFunObject function object.  The function simpleFunObject is a functional object and we can assign it variable and called render() method. Render refers to show output in the browser and utilize the document object to manipulate DOM elements.

In the Javascript Scoping is static, it is determined by the nesting of syntactic constructs. The variable scoping is actually determined by a simple static scoping rule. This rule can follow as, whenever the runtime searches for a variable reference, the search will be performed first locally. When a variable declaration is not found in second highlight headline in code, search will perform first in local then it search continue toward the parent object, if still not found, then this process will continue recursively to next parent, so on and so forth, till it reaches a global variable definition, if it is still not found then a reference error will be generated for this variable.