Thursday 20 October 2016

Variable scope in JavaScript


See the example code below :

function Test1() {
    // 1)  Declare using var            
    if (true) {
        var x = 10;
    }
    console.log(x); // 10

    // 2) Declare using let
    if (true) {
        let x = 5;
        console.log(x); // 5
    }
    console.log(x); // 10

    // 3) Declare using const
    if (true) {
        const x = 8;
        console.log(x); // 8
    }
    console.log(x); // 10
}

1. Declare variable using var
If you declare variable in JavaScript using var keyword, variable is accessible through out 
the function even thought you declared it inside any loop (e.g if, while...). See the above 
example where x is declared using var keyword inside if loop still it is accessible 
through out the function scope. If you  declare variable without giving any keyword then it becomes global variable even if you declare it inside the function (throw ReferenceError in strict mode). 

2. Declare variable using let 
 let keyword allows you to declare variable withing the limited scope of the block, 
statement or expression. Variables declared using let have their scope to the block 
in which they are defined, as well as in any contained sub-blocks. Unlike var, let does not create a property on the global object. E.g.

var x = 'global';
        let y = 'global';
        console.log(this.x); // "global"
console.log(this.y); // undefined 

You can not re-declare same variable in same scope using let. E.g
        switch (x) {
            case 0:
                let x;
                break;
    
            case 1:
                let x; // SyntaxError for redeclaration.
                break;
    }

See the second example in first code variable scope is limited to block even if you change 
the value it won’t reflect outside the scope.

1. Declare variable using const 
Const keyword is block scoped much like let. It creates a constant that can be either global
or local to the function in which it is declared. Constant initialization is required. You must
specify its value while declaring the constant. Constants once created never change their 
value and can’t be re-declared. The const declaration creates a read-only reference to a 
value but not all values are immutable. If you create object you can alter the values of 
object but can not reassign. E.g.

const A = 10;
// A = 12 // throw error;

const myObj = { "Name""AP" };
// myObj = { "City": "AHD" }; // throw error;

// Object.freeze(myObj);
myObj.Name = "Ajay" // works fine if object is not freezed