Variable scopes

Variable Scopes

When you declare a variable, it is available anywhere in that scope, as well as any lower/inner scopes.


function foo(){
    var a=3;
    function bar(){
        var b=10;
        console.log(a,b);  //3,10

        function biz(){
            var c=20;
            console.log(a,b,c)  //3,10,20
        }

        biz();  //call inner  function
    }
    bar(); //call inner function
}

foo();

Notice that c is not available inside of bar(), because it’s declared only inside the inner biz() scope, and that b is not available to foo() for the same reason.

If you try to access a variable’s value in a scope where it’s not available, you’ll get a ReferenceError thrown.

If you try to set a variable that hasn’t been declared, you’ll either end up creating a variable in the top-level global scope (bad!) or getting an error, depending on “strict mode”.

function foo() {
a = 1; // `a` not formally declared
}
foo();
a; // 1--oops, auto global variable :(

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

With the introduction of ES6 in 2015 two more keywords, let and const came into the picture. var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted and initilized with undefined.

console.log(a); // ReferenceError: a is not defined
let a = 12;

Like varlet variables are hoisted to the top of their containing block. However, the actual assignment (initialization) remains in its original position. You can use a let variable before its explicitly declared, but its value will be uninitialized until explicitly assigned.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form