Preparation
πŸ’‘ ⏐ JavaScript Questions
6. Let, Var, Const

var, let, and const in JavaScript

Understanding let, var, and const in JavaScript is crucial for properly declaring variables and managing their scope and immutability. Let's explore each of these variable declaration keywords:

1. var:

  • Scope: Variables declared with var are function-scoped. They are accessible within the function they are declared in, regardless of block scope.
  • Hoisting: Variables declared with var are hoisted to the top of their function or global scope. This means they can be accessed before they're declared, but their value will be undefined.
  • Re-declaration: Variables declared with var can be re-declared within the same scope without throwing an error.
  • Example:
    function example() {
      var x = 10
      if (true) {
        var y = 20
        console.log(x) // Output: 10
      }
      console.log(y) // Output: 20
    }

2. let:

  • Scope: Variables declared with let are block-scoped. They are accessible only within the block they are declared in, such as within loops or conditionals.
  • Hoisting: Variables declared with let are hoisted to the top of their block scope, but they're not initialized. Accessing them before declaration results in a ReferenceError.
  • Re-declaration: Variables declared with let cannot be re-declared within the same scope. Attempting to do so will result in a syntax error.
  • Example:
    function example() {
      let x = 10
      if (true) {
        let y = 20
        console.log(x) // Output: 10
      }
      console.log(y) // ReferenceError: y is not defined
    }

3. const:

  • Scope: Variables declared with const are block-scoped, just like variables declared with let.
  • Immutability: Variables declared with const are read-only. Once assigned, their value cannot be changed or reassigned.
  • Hoisting: Variables declared with const are hoisted to the top of their block scope, but like let, they're not initialized. Accessing them before declaration results in a ReferenceError.
  • Example:
    function example() {
      const x = 10
      if (true) {
        const y = 20
        console.log(x) // Output: 10
      }
      console.log(y) // ReferenceError: y is not defined
    }

Conclusion:

  • Use var for variables that need function scope or when compatibility with older code is required.
  • Use let for variables that need block scope and may be reassigned.
  • Use const for variables that need block scope and will not be reassigned, promoting immutability.

Understanding the differences between let, var, and const helps in writing cleaner, more predictable code and avoiding common pitfalls associated with variable scoping and reassignment.