Javascript Tips: compare const and let and var statements

By JoeVu, at: 18:33 Ngày 25 tháng 11 năm 2023

Thời gian đọc ước tính: 3 min read

Javascript Tips: compare const and let and var statements
Javascript Tips: compare const and let and var statements

In JavaScript, let, const, and var are used to declare variables, but they have some differences in terms of scope, hoisting, and mutability.

  1. var (Variable Declaration):

    • Variables declared with var are function-scoped, meaning their scope is limited to the function in which they are defined.
    • var variables are hoisted to the top of their scope during the execution phase, which means you can use the variable before it's declared in the code.
    • var variables can be redeclared and reassigned.
    function variable_declaration() {
      var x = 10;
      if (true) {
        var x = 20; // Same variable as above, not a new one
        console.log(x); // Outputs 20
      }
      console.log(x); // Outputs 20, not 10
    }

  2. let (Block-scoped Declaration):

    • Variables declared with let are block-scoped, meaning their scope is limited to the block (a pair of curly braces) in which they are defined.
    • let variables are also hoisted, but they are not initialized until the interpreter reaches their declaration in the code.
    • let variables can be reassigned, but not redeclared in the same scope.
    function variable_declaration() {
      let x = 10;
      if (true) {
        let x = 20; // Different variable than the one outside the block
        console.log(x); // Outputs 20
      }
      console.log(x); // Outputs 10, not affected by the inner block
    }

  3. const (Constant Declaration):

    • Variables declared with const are block-scoped like let.
    • const variables must be assigned a value when declared, and that value cannot be changed or reassigned.
    • Like let, const variables are not hoisted until their declaration.
    function variable_declaration() {
      const x = 10;
      // x = 20; // This would result in an error, as const variables cannot be reassigned
      console.log(x); // Outputs 10
    }

In general, it's a good practice to use const by default and only use let when you know the variable's value will change. var is used less frequently in modern JavaScript due to its function-scoping behavior and hoisting quirks. Using const and let can help prevent unintended reassignments and improve code clarity.


Liên quan

Theo dõi

Theo dõi bản tin của chúng tôi và không bao giờ bỏ lỡ những tin tức mới nhất.