Var, Let, and Const in JavaScript

person shubham sharmafolder_openJAVASCRIPTlocal_offeraccess_time October 30, 2025

Var, Let, and Const in JavaScript

Definition: In JavaScript, var, let, and const are used to declare variables, but they differ in scope, hoisting behavior, and reassignment rules. Understanding these differences helps you write cleaner and more predictable code.


1. var — The Old Way

The var keyword has been part of JavaScript since the beginning. It declares a variable that is function-scoped (not block-scoped) and can be re-declared or updated within the same scope.

Hoisting Behavior: Variables declared with var are hoisted and initialized as undefined. You can access them before declaration, but they won’t have a defined value.


2. let — The Modern, Block-Scoped Variable

Introduced in ES6 (ECMAScript 2015), let provides block scope, meaning the variable is accessible only within the nearest set of curly braces ({}).

Hoisting Behavior: Variables declared with let are hoisted but remain in the Temporal Dead Zone (TDZ) until initialized. Accessing them before declaration throws a ReferenceError.

Redeclaration: let does not allow redeclaration within the same scope, but reassignment is allowed.


3. const — The Immutable Reference

const is also block-scoped like let, but it must be initialized at the time of declaration and cannot be reassigned.

However, note that const only prevents reassignment of the variable itself, not changes to the contents of objects or arrays.


4. Scope Differences Summary

Here’s a visual summary of how these variables behave inside different scopes:


5. Comparison Table

Feature var let const
Scope Function-scoped Block-scoped Block-scoped
Hoisting Yes (initialized as undefined) Yes (TDZ until initialization) Yes (TDZ until initialization)
Redeclaration Allowed Not allowed Not allowed
Reassignment Allowed Allowed Not allowed
Initialization Required No No Yes

6. Best Practices & Interview Tips

  • Always prefer const for variables that won’t be reassigned.
  • Use let for variables whose values will change.
  • Avoid var unless working with legacy code — it can cause unexpected behavior due to hoisting and function scoping.
  • In interviews, emphasize that const does not make data immutable — only the variable reference.

Example: Real-World Use Case

Here’s a small example that combines all three in one block:

Output:


Key Takeaways

  • var — Function-scoped, hoisted, can be re-declared.
  • let — Block-scoped, cannot be re-declared, can be reassigned.
  • const — Block-scoped, cannot be re-declared or reassigned.
  • Prefer let and const in modern JavaScript for clean and safe code.

In short: var belongs to the old days of JavaScript; let and const bring structure, safety, and clarity to variable management in modern applications.

warningComments are closed.