DIFFERENCE BETWEEN LET, VAR, AND CONST IN JAVASCRIPT

Difference Between let, var, and const in JavaScript

Difference Between let, var, and const in JavaScript

Blog Article

In JavaScript, let, var, and const are keywords used to declare variables. Although they all create variables, they behave differently in terms of scope, hoisting, reassignment, and redeclaration. Understanding these differences is essential for writing clean, bug-free code.


1. var – The Old Way

  • Scope: Function-scoped
    Variables declared with var are scoped to the nearest function, not block (like if/for).

  • Hoisting: Yes
    var declarations are hoisted to the top of their scope and initialized with undefined.

  • Reassignment: Allowed

  • Redeclaration: Allowed

2. let – The Modern Variable Declaration

  • Scope: Block-scoped
    let variables are only accessible within the block {} where they are declared.

  • Hoisting: Yes, but not initialized
    Variables declared with let are hoisted but not initialized, so accessing them before declaration causes a ReferenceError (Temporal Dead Zone).

  • Reassignment: Allowed

  • Redeclaration: Not allowed within the same scope

3. const – Constant Variable Declaration

  • Scope: Block-scoped (like let)

  • Hoisting: Yes, but not initialized (Temporal Dead Zone applies)

  • Reassignment: Not allowed (variable must be initialized at declaration)

  • Redeclaration: Not allowed within the same scope

  • Note: For objects and arrays declared with const, you cannot reassign the variable itself, but you can modify the contents:


Summary Table

Feature var let const
Scope Function-scoped Block-scoped Block-scoped
Hoisting Yes (initialized as undefined) Yes (not initialized, TDZ) Yes (not initialized, TDZ)
Reassignment Allowed Allowed Not allowed
Redeclaration Allowed Not allowed (in same scope) Not allowed (in same scope)
Temporal Dead Zone No Yes Yes

When to Use Each?

  • Use var if you need compatibility with very old JavaScript environments (not recommended in modern code).

  • Use let when you need a variable whose value changes and whose scope is limited to a block.

  • Use const for variables that should never be reassigned, providing safer, more predictable code.


Conclusion

Understanding the differences between var, let, and const helps avoid subtle bugs related to scope and variable mutation. Modern JavaScript development favors let and const due to their clearer, block-scoped behavior and safer patterns.

Report this page