Friday, March 22, 2024

What is the difference between let and var in JavaScript?

**Scope:**

   - `let`: Variables declared with `let` are limited to the block they are declared in. They are only accessible within the block of code where they are defined.

   - `var`: Variables declared with `var` are function-scoped or globally scoped. They are accessible throughout the entire function where they are defined, or globally if not within a function.


// Using let

function letExample() {

    let x = 10;

    if (true) {

        let y = 20;

        console.log(x); // Output: 10

        console.log(y); // Output: 20

    }

    console.log(x); // Output: 10

    console.log(y); // ReferenceError: y is not defined

}

letExample();

// Using var

function varExample() {

    var x = 10;

    if (true) {

        var y = 20;

        console.log(x); // Output: 10

        console.log(y); // Output: 20

    }

    console.log(x); // Output: 10

    console.log(y); // Output: 20 (accessible due to var's function scope)

}

varExample();


In the `letExample`, `x` is accessible within the function `letExample`, but `y` is only accessible within the `if` block where it's defined. Trying to access `y` outside the `if` block will result in a `ReferenceError`.


In the `varExample`, both `x` and `y` are accessible within the entire `varExample` function, even though `y` is defined inside the `if` block. This is because variables declared with `var` are function-scoped.