let vs var in JavaScript

Before ECMAScript 6, JavaScript was function scope language. It means that variable was visible only in the function in which it was defined. There was nothing like block scope ( like other language ) where a variable can only be accessed in particular block ( { ... } ) in which it was defined.

Let us have a look at an example.


function foo(){
    var functionVar = "this is function var";

    console.log(functionVar);
    //output: "this is function var"

    if(/*** some condition which is true ***/){
        var ifVar = "this is variable in if condition";
        console.log(ifVar);
        //output: "this is variable in if condition"
        console.log(functionVar);
        //output: "this is function var"
    }
    console.log(ifVar);
    //output: "this is variable in if condition"
}

foo();
                    

As you can see in above code, we have a function foo which declares a variable functionVar. Now functionVar is visible in whole function even inside if condition because it is in global scope to if condition.
But we have declared a variable ifVar in if condition. So ifVar is local variable to if condition. But when you access it outside of if condition, you can access it ( but not outside of function ).

So every variable declared by var keyword does not obey block. It can be accessed outside of block ( in which they are declared ). for loop, while loop, do..while loop, if are the example of block.

So when you need the variable only be accessed inside the block it's been declared, use let keyword.
let us have a look at an example.


function foo(){
    var functionVar = "this is function var";
    let functionVar1 = "this is function var with let";
    console.log(functionVar);
    //output: "this is function var"
    console.log(functionVar1);
    //output: "this is function var with let"
    if(/*** some condition which is true ***/){
        let ifVar = "this is variable in if condition";
        console.log(ifVar);
        //output: "this is variable in if condition"
        console.log(functionVar);
        //output: "this is function var"
        console.log(functionVar1);
        //output: "this is function var with let"
    }
    console.log(ifVar);
    //output: error
}

foo();
                    

In above code, we have declared functionVar1 and ifVar with let keyword. You can access functionVar1 in whole function because it is declared inside function. But you can not access ifVar outside of if condition because let makes the variable local to particular block in which it is declared.

Summary let vs var

Features let var
Scope Block scope Function scope
Life time Block in which it is declared Function in which it is declared

Conclusion

In this section, you learned about difference between let and var.
In next section, you will learn about data types in JavaScript.