Let Vs Var : Battle between modern javascript keywords

Let Vs Var : Battle between modern javascript keywords DasJs

Let Vs Var : Let's the battle begins

There are two important javascript keywords ( let and const ) introduced by ECMAScript 2015. These two keywords provide Block scope in Javascript.

Before this, Javascript had only two type of scopes i) Global Scope and ii) Local Scope

JavaScript Block Scope

Variables declared with the var keyword inside a block {} can be accessed from outside the block.


{ 
    var x = 2; 
}
// x CAN be used here

Variables declared with the let keyword can have Block Scope and can't be accessed from outside of the block.


{ 
    let x = 2;
}
// x can NOT be used here

 

Let's check out some examples:


var x = 10;
// Here x is 10
{ 
    var x = 2;
    // Here x is 2
}
// Here x is 2

Here var x can not have block scope. That'why the value of x of line 1  overwrites by the value of x of line 4.


var x = 10;
// Here x is 10
{ 
    let x = 2;
    // Here x is 2
}
// Here x is 10

Here let x can have block scope. It means the value of x with prefix let has scope inside block only. This value doesn't available outside of the block.

Let keyword with Loop Scope


var i = 5;
for (var i = 0; i < 10; i++) {
    // some statements
}
// Here i is 10

Here, using var,  variable declared on line number 1. Then redeclared inside the loop. Value of var i overwrites everytime loop runs.

Using let in a loop:


let i = 5;
for (let i = 0; i < 10; i++) {
    // value of available inside this loop only
}
// Here i is 5

Here, using let,  variable declared on line number 1 has scope globally. Then variable redeclared inside the loop has scope inside the loop.

Redeclaring a var variable with let, in the same scope, or in the same block, is not allowed:

Example


var x = 2;       // Allowed
let x = 3;       // Not allowed

{
    var x = 4;   // Allowed
    let x = 5   // Not allowed
}

Redeclaring a variable with let, in the same scope, or in the same block, is not allowed:

Example


let x = 2;       // Allowed
let x = 3;       // Not allowed

{
    let x = 4;   // Allowed
    let x = 5;   // Not allowed
}

Redeclaring a variable with let, in another scope, or in another block, is allowed:

Example


let x = 2;       // Allowed

{
    let x = 3;   // Allowed
}

{
    let x = 4;   // Allowed
}

With the above explanation, I can surely tell that now you have the total idea about the difference between let and var variables.