「 Article 」 March 08, 2020

Difference? var, let and const

Words count 2.8k Reading time 3 mins. Read count 1000000

Var

var variables can be redefined or updated.

    var width = 100;
    console.log(width); // 100
    var width = 200;
    console.log(width); // 200

Same variable name would not result in error.

Scope

they’re function scope, which means that they are only available inside the function that they are created in. However, if they are not declared in a function, then they are globally scoped, and they’re available in the whole window.

Variable Hoisting

Another feature of var is variable hoisting which allows a variable declared after it has been used.

    x = 5; // Assign 5 to x
    console.log(x)  // log 5
    var x; // Declare x

Whereas let and const don’t support such feature.

let and const

Scope

let and const are block scope, which means any time you’ve got a set of curly brackets you have block scope.

    const key = 'abc123';
    let points = 50;
    let winner = false;

    if(points > 40) {
       let winner = true
    }
    console.log(winner)  // log false

Immutable

let variables are mutable which means the values of variables can be updated later

let name = "eric"
name = "jack"
console.log(name)  // log "Jack"

const variables are immutable resulting in their values can not be updated

    const age = 18
    age = 20  // error occurs

However, if a JavaScipt is declared with const varibale. the value inside can be updated. For example,

    const dog = {name:"mimi",age:"4"}
    dog.name = "kiki"
    console.log(dog)  // log { name: 'kiki', age: '4' }

So if you do want to a JavaScript object immutable, the following code can help:

    const wes = Object.freeze(dog);
    console.log(wes)  // log {name:"kiki",age:"4"}
    wes.name = "new name"
    console.log(wes)  // still log {name:"kiki",age:"4"}
0%