Home / javascript / What are the differences between var, let and const in JavaScript?

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have some differences in terms of scope, hoisting, and mutability:

var:

Variables declared with var are function-scoped or globally scoped, but not block-scoped.

They are hoisted to the top of their function or global scope, which means you can access them before they are declared.

You can redeclare a variable using var within the same scope.

var variables can be reassigned.

function example() {
    var x = 10;
    if (true) {
        var x = 20; // This will overwrite the previous value of x
        console.log(x); // Output: 20
    }
    console.log(x); // Output: 20
}

let:

Variables declared with let are block-scoped, which means they are only accessible within the block they are defined in.

They are not hoisted to the top of the block.

You cannot redeclare a variable using let within the same scope.

let variables can be reassigned.

function example() {
    let x = 10;
    if (true) {
        let x = 20; // This creates a new variable x that shadows the outer x
        console.log(x); // Output: 20
    }
    console.log(x); // Output: 10
}

const:

Variables declared with const are block-scoped like let.

They must be initialized when declared and cannot be reassigned.

However, const does not make objects immutable. You can still modify the properties of a const object.

const y = 3.14;
y = 3; // This will throw an error

const person = {
    name: 'John',
    age: 30
};
person.age = 40; // This is allowed

In general, it’s recommended to use const by default for variable declaration, unless you know the variable will need to be reassigned later. Use let when you need a variable that may change its value, and avoid using var due to its hoisting behavior and potential issues with scope.

About admin

Check Also

What is hoisting in javascript with example?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the …

Leave a Reply

Your email address will not be published. Required fields are marked *