How do let and const differ from var?
1. Main differences
| Criterion | var | let | const |
|---|---|---|---|
| Scope | Function or global | Block ({ ... }) | Block ({ ... }) |
| Hoisting | Hoisted and initialized to undefined | Hoisted, but not initialized (error if accessed before declaration) | Hoisted, but not initialized (error if accessed before declaration) |
| Re-declaration | Allowed within the same scope | Error | Error |
| Reassigning the value | Allowed | Allowed | Not allowed |
| Added to the window object (in the browser) | Yes (window.varName) | No | No |
2. Scope
var - function scope
javascript
if (true) {
var a = 10;
}
console.log(a); // 10 (accessible outside the block!)let / const - block scope
javascript
if (true) {
let b = 20;
const c = 30;
}
console.log(b); // ReferenceError
console.log(c); // ReferenceError
letandconstonly "live" inside a{}block.
3. Hoisting (variable hoisting)
All variables are "hoisted" to the top of their scope,
but var is initialized with the value undefined,
while let and const fall into the Temporal Dead Zone (TDZ).
javascript
console.log(a); // undefined (var is hoisted)
var a = 5;
console.log(b); // ReferenceError (in the TDZ)
let b = 10;
console.log(c); // ReferenceError (in the TDZ)
const c = 15;4. Re-declaration and reassignment
javascript
var x = 1;
var x = 2; // allowed
console.log(x); // 2
let y = 1;
let y = 2; // SyntaxError: Identifier 'y' has already been declared
const z = 1;
z = 2; // TypeError: Assignment to constant variable5. Behavior with objects and arrays under const
const protects the reference, not the contents.
javascript
const user = { name: 'Tim' };
user.name = 'Alex'; // the property can be changed
console.log(user.name); // 'Alex'
user = {}; // The object itself cannot be reassigned6. Behavior in the browser (global variables)
javascript
var x = 10;
let y = 20;
const z = 30;
console.log(window.x); // 10
console.log(window.y); // undefined
console.log(window.z); // undefinedvar adds the variable to the global object (window, globalThis),
while let and const do not, which makes the code safer.
7. Summary - how to use them
| Situation | What to use | Why |
|---|---|---|
| The variable needs to change | let | Safer than var, with block scope |
| The variable should not change | const | Explicitly shows immutability |
| Legacy code (pre-ES6) | var | Outdated, use only to support old projects |
A simple rule of thumb
const- by default.let- when you need to change the value.var- never use it in modern code.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.