乐闻世界logo
搜索文章和话题

How are ‘let’, ‘var’, and ‘const’ different?

1个答案

1

Differences Between let, var, and const

These three keywords are used to declare variables in JavaScript, but they have important differences in terms of scope, hoisting behavior, and reassignment capability.

  1. var

    • Scope: Variables declared with var have function scope. If declared inside a function, they are accessible only within that function. If declared outside a function, they are global variables.
    • Hoisting: Variables declared with var are hoisted to the top of the function or global code, but only the variable name is hoisted, not the assignment.
    • Redeclaration: The same variable can be declared multiple times within the same scope.
    • Example:
      javascript
      console.log(x); // logs undefined instead of throwing an error var x = 5;
  2. let

    • Scope: Variables declared with let have block scope (i.e., within {}), making them more suitable for controlling variable scope in loops and conditional statements.
    • Hoisting: Variables declared with let are not hoisted to the top of the code block. Attempting to access the variable before declaration results in a ReferenceError.
    • Redeclaration: Redeclaring the same variable within the same scope is not allowed.
    • Example:
      javascript
      if (true) { let y = 5; } console.log(y); // throws an error, y is not defined
  3. const

    • Scope: Like let, const has block scope.
    • Hoisting: Similar to let, const is not hoisted.
    • Redeclaration: Redeclaring the same variable within the same scope is not allowed.
    • Immutability: Variables declared with const are constants and cannot be re-assigned after initialization. However, if the constant is an object or array, its properties or elements can be modified.
    • Example:
      javascript
      const z = 10; z = 5; // throws an error because const variables cannot be re-assigned const arr = [1, 2, 3]; arr.push(4); // works because we are modifying the array's contents, not the reference console.log(arr); // outputs [1, 2, 3, 4]

In summary, let and const are keywords introduced in ES6. Compared to var, they provide more precise control over variable scope and stricter usage rules, which helps in writing safer and more maintainable code.

2024年8月3日 16:32 回复

你的答案