let, var and const

let, var and const

The blog will help you understand the difference between let, var and const.

let

let allows you to declare variables that are limited to the scope of a block statement or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. That means that a variable declared with the let keyword is only and only limited to its scope or context, using it outside that scope will give a variable not defined error.

{
    let var2 = "js";
}
    console.log(var2);

The following code snippet has the variable var2 declared within a scope. If we try to access the following variable outside that scope the following error is encountered.

image.png

If we modify the following code and try to access the variable in the code block, it will surely be accessible.

{
    //new block
    let var2 = "js";
    console.log(var2);
}

The following code will work and will work perfectly.

image.png

var

The variables declared with the var keyword have global scope in the program. The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it or, for variables declared outside any function, global. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value unless another assignment is performed.

// global scope
{  // scope 1
       { //scope 2
        var var1="Let's learn js";
        console.log(var1);
        { //scope 3
            var var1 ="javaScript";
            console.log(var1);
        }
    }
    console.log(var1);
}
    console.log(var1);

The above code snippet has no variable var1 declared globally and in scope 1, still the program executes and gives the below output as every variable declared using var has always a global scope.

image.png

const

Variable declared with const keyword are also block scoped like let but its value once declared remains constant throughout the program and reassignment is not allowed. These variables never become part of window object like let and unlike var.

//global scope
{ 
    //local scope
     const var1 = 5;
     console.log(var1);
 }
     console.log(var1);

The following code snippet demonstrates that const is block scoped.

image.png

Also, in addition to that, the value always remains constant and change in value is not allowed here.

const var1 = 10;
var1 =20; // reassignment not allowed 
console.log(var1);

Gives error on console.

image.png

That is the basic difference between var, let and const in JavaScript. I Hope, it was meaningful.