What is difference between let and var keyword in javascript?

Dung Do Tien May 14 2020 499

I am a beginner in Javascript, I usually var keyword to declare a variable, but in JS has more let keyword, it also used to declare a variable, so what is difference between let and var keyword?

Thanks for any explanation.

Have 1 answer(s) found.
  • S

    Sandeep Kumar May 14 2020

    The main difference is the scoping rules. let keyword is introduced by ES6, it provides Block Scope variables.
    Before ES6, JavaScript only provided two scope types are Global Scope and Function Scope

    1. Var

    The var keyword is global Scope, If you declare a variable outside function you can use it anywhere. If you declare inside function this variable only use inside that function, you can not access that variable outside function.

    var age = 10
    // You can use age here;
    
    function getAge(){
        // You also use age here;
    }
    
    function getAge(){
       var age = 10;
    }
    // Code here can not use age 

    About redeclaring variables in {} block with the same name new value will assign.

    var greeting = "hello";
    var times = 5;
    
    if (times > 2) {
        var greeting = "Hello instead"; 
    }
    
    console.log(greeting); //"Hello instead"

    In this example, you can see new value is assigned. If your function very long you will very difficult to control the value of a variable.

    2. Let

    As I note as the above let keyword is a block scope. 

    let variables are scoped to the immediate enclosing block denoted by { }

    var age = 10;
    if(age > 7){
       let count = 10;
    }
    console.log(count); // Uncaught ReferenceError: count is not defined
    // You can not use count variable here
    

    About redeclaring variables in {} block with the same param new value will NOT assign to the variable.

    var greeting = "hello";
    var times = 5;
    
    if (times > 2) {
        let greeting = "Hello instead"; 
    }
    
    console.log(greeting); //"hello"

    3. Summary

    - In function scope variables declared with var and let are quite similar when declared inside a function.

    - In global scope variables declared with var and let are quite similar when declared outside a block.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close