In JavaScript, let, const, and var are used to declare variables — but they behave differently in terms of scope, reassignment, and hoisting.
1. var
- Scope: Function-scoped.
- Reassign: ✅ Yes.
- Redeclare: ✅ Yes.
- Hoisting: Variables declared with
varare hoisted and initialized withundefined. -
Example:
function test() { console.log(a); // undefined var a = 10; console.log(a); // 10 } test();
2. let
- Scope: Block-scoped.
- Reassign: ✅ Yes.
- Redeclare: ❌ No (in the same scope).
- Hoisting: Hoisted but not initialized (Temporal Dead Zone).
-
Example:
{ let x = 5; console.log(x); // 5 } // console.log(x); // ❌ ReferenceError
3. const
- Scope: Block-scoped.
- Reassign: ❌ No (but object properties can be mutated).
- Redeclare: ❌ No.
- Hoisting: Hoisted but not initialized (Temporal Dead Zone).
-
Example:
const y = 10; // y = 20; // ❌ TypeError const obj = { name: 'Teekam' }; obj.name = 'Singh'; // ✅ Allowed (mutating property) console.log(obj.name); // Singh
✅ When to use:
var: ❌ Avoid in modern JS.let: When you need to reassign values.const: Default choice when value won’t change.