Javascript: Var vs Let vs Const?

Standard

In JavaScript, var, let, and const are used to declare variables, but they have different scoping rules and behaviors. Here’s a breakdown of the differences between them:

  1. var:
    • Variables declared with var are function-scoped or globally scoped, depending on where they are declared. They are not block-scoped.
    • This means that a variable declared with var is accessible throughout the entire function in which it is declared or throughout the global scope if declared outside of any function.
    • var declarations are hoisted to the top of their scope during the compilation phase, so you can access them before they are declared in your code (this can lead to unexpected behavior).
    • var variables can be re-declared and updated within their scope.
  2. let:
    • Variables declared with let are block-scoped, which means they are confined to the nearest enclosing block, such as a loop or an if statement.
    • let variables are not hoisted to the top of their block. They are only accessible after they are declared in the code.
    • Unlike var, you cannot re-declare a variable using let in the same scope.
    • let variables can be updated after declaration, meaning you can change their value.
  3. const:
    • Variables declared with const are also block-scoped like let.
    • However, const variables are constants, which means their value cannot be reassigned after it’s assigned once. This makes them suitable for values that should remain constant throughout their scope.
    • Like let, const variables are not hoisted and are only accessible after they are declared in the code.
    • Similar to let, you cannot re-declare a variable using const in the same scope.

Here’s a quick example to illustrate the differences:

function example() {
    var varVariable = "I am var";
    let letVariable = "I am let";
    const constVariable = "I am const";

    if (true) {
        var varVariable = "I am still var";
        let letVariable = "I am still let"; // This creates a new block-scoped variable
        // const constVariable = "This will cause an error"; // Cannot redeclare in the same scope
    }

    console.log(varVariable); // Outputs: "I am still var"
    console.log(letVariable); // Outputs: "I am let"
    console.log(constVariable); // Outputs: "I am const"
}

example();

In modern JavaScript, it’s generally recommended to use let and const over var due to their more predictable scoping and behavior. Use let when you need to reassign a variable, and use const when you want to ensure a variable’s value remains constant.

Leave a Reply

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