Difference between var, let and const keyword in JavaScript

 In JavaScript, We can declare a variable using below keywords:

  1. var
  2. let
  3. const
Below are the difference between these keywords:

Scope:
The scope of the "var" keyword is the global scope. Means variables defined outside the function can be accessed globally.

<script>
    var a = 20;
    function fun() {
        if (true) { 
            var b = 30 // declared in "if" block but can be accessible outside of this "if" block.
        }
        console.log(b);
        console.log(a);
    }
    fun();
</script>

Output: 
30
20

The scope of a "let" variable is only block scoped. It can’t be accessible outside the particular block. Have a look at below example:

<script>
    let a = 20;
    function fun() {
        if (true) { 
            let b = 30
        }
        console.log(b);
        console.log(a);
    }
    fun();
</script>
Output: 
ReferenceError: b is not defined
20

Re-declaration
User can re-declare variable using "var" and user can update variable value. Have a look at below example:

<script> 
    // declare the variable.
    var a = 20
   
    // Re-declare the variable
    var a = 30 // No error with this re-declaration.
 
    // Update the variable value
    a = 40
    
    console.log(a);
</script> 
Output: 40

Users cannot re-declare the variable defined with the "let" keyword but can update it. Have a look at below example:

<script> 
    // declare the variable.
    let a = 20
   
    // Re-declare the variable
    let a = 30 // It is not allowed. Uncaught Syntax Error: Identifier 'a' has already been declared.
 
    // Update the variable value
    a = 40 // It is allowed
    
    console.log(a);
</script> 
Output: 
Uncaught Syntax Error: Identifier 'a' has already been declared.
40

"const" keyword:
"const" keyword has all the properties that are the same as the "let" keyword, except the user cannot update it's value.

<script>
    const a = 20;
    function fun() {
        a = 30  // It is not allowed. Type Error: Assignment to constant variable.
        console.log(a);
    }
    fun();
</script>

Output: 
Type Error: Assignment to constant variable.
20

Users cannot change the properties of an object declared using "const" keyword, but user can change the value of properties of a object declared using "const" keyword.

<script>
    const address = {
        city: 'Jaipur',
        state: 'Rajasthan'
    }
     
    // It is allowed
    address.city  = 'Udaipur';
 
    // It is not allowed
    address = {
        city: 'Udaipur',
        state: 'Rajasthan'
    }
</script>


Comments

Popular posts from this blog

Salesforce Record Id

Salesforce External ID