JavaScript Basic
What are the differences between var, let, and const in JavaScript?
var vs let vs const
Scope
if (true) {
var a = 1; // function-scoped (or global)
let b = 2; // block-scoped
const c = 3; // block-scoped
}
console.log(a); // 1 (accessible)
console.log(b); // ReferenceError
console.log(c); // ReferenceError
Hoisting
console.log(x); // undefined (var hoisted, not initialized)
var x = 5;
console.log(y); // ReferenceError (Temporal Dead Zone)
let y = 5;
Re-declaration
var a = 1; var a = 2; // ✅ OK
let b = 1; let b = 2; // ❌ SyntaxError
const c = 1; const c = 2; // ❌ SyntaxError
Re-assignment
var a = 1; a = 2; // ✅ OK
let b = 1; b = 2; // ✅ OK
const c = 1; c = 2; // ❌ TypeError
Comparison
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | ✅ (undefined) | ✅ (TDZ) | ✅ (TDZ) |
| Re-declare | ✅ | ❌ | ❌ |
| Re-assign | ✅ | ✅ | ❌ |
Best practice: Default to
const, useletwhen reassignment is needed, avoidvar.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
