Advance JavaScript

JavaScript – Let and Const Variable


In JavaScript, there are mainly three types of variable.

  • Var
  • Let (Introduced in ES6)
  • Const (Introduced in ES6)

Var: In this type of variable, if you can assign a value and later on redeclare and reassign different value to the same variable. The value will be changed with the new one without any errors.

Var variables have global scope. So, even if variable value is updated within a function, its updated value can be used outside of function.

Example:

<script>
    var name = "Mayank";
    var name = "Deepak";
    console.log(name);
</script>

#Output
Deepak

Here, the final value of name will be ‘Deepak’. As it is redeclared and reassigned with this value. So, var type variable returns last assigned value to that variable.

<script>
    var name = "Mayank";
    var name = "Sumit";
    if(1==1){
        var name = "Nikhil";
    }
    console.log(name);
</script>

#Output
Nikhil

Here, the final value of name will be ‘Nikhil’.


Let: Let type of variables cannot be re-declared. So, if you try to redeclare similar to var type, it will show error. You can reassign new value to the variable but cannot redeclare.

Example:

<script>
    let name = "Mayank";
    let name = "Deepak";
    console.log(name);
</script>

#Output
Uncaught SyntaxError: Identifier 'name' has already been declared
<script>
    if(1==1){
        let a = "Deepak";
        console.log(a);
    }
    console.log(a);
</script>

#Output
Deepak
Uncaught ReferenceError: a is not defined

As Unlike ‘var’, ‘let’ type variable can not be redeclared. Also, let has block scope only, so we cannot read let type variable outside the block.


Const: Constant type variable value remains unchanged. You can not even re-assign different value. It means once the value is assigned to const type variable, it will be unchanged.

Example:

<script>
    const name = "Mayank";
    const name = "Sudhir";
    console.log(name);
</script>

#Output
Uncaught SyntaxError: Identifier 'name' has already been declared