DEV Community

Artem
Artem

Posted on

var, let, const in JavaScript - summary of differences between them

Summary of Differences.
If you, like me, are tired of this interview question.

Scope:

var: Function or global scope.

let: Block scope.

const: Block scope.

Hoisting:

var: Hoisted and initialized with undefined.

let: Hoisted but not initialized (temporal dead zone).

const: Hoisted but not initialized (temporal dead zone).

Re-declaration:

var: Can be re-declared within the same scope.

let: Cannot be re-declared within the same scope.

const: Cannot be re-declared within the same scope.

Immutability:

var and let: Mutable references.

const: Immutable reference (the reference cannot change, but the value can if it's an object).

Examples

var

function varExample() {
    console.log(x); // undefined (due to hoisting)
    var x = 10;
    if (true) {
        var x = 20; // Same variable, function-scoped
        console.log(x); // 20
    }
    console.log(x); // 20 (same variable as above)
}

varExample();
Enter fullscreen mode Exit fullscreen mode

let

function letExample() {
    // console.log(y); // ReferenceError (temporal dead zone)
    let y = 10;
    if (true) {
        let y = 20; // Different variable, block-scoped
        console.log(y); // 20
    }
    console.log(y); // 10 (original variable)
}

letExample();
Enter fullscreen mode Exit fullscreen mode

const

function constExample() {
    // console.log(z); // ReferenceError (temporal dead zone)
    const z = 10;
    if (true) {
        const z = 20; // Different variable, block-scoped
        console.log(z); // 20
    }
    console.log(z); // 10 (original variable)

    const obj = { name: "Alice" };
    obj.name = "Bob"; // Allowed (the object itself is mutable)
    console.log(obj.name); // Bob

    // obj = { name: "Charlie" }; // TypeError (can't reassign const)
}

constExample();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)