var, let, and const in JavaScriptThey are used to declare variables in JavaScript. But they behave differently in terms of scope, reassignment, and hoisting.
var — The Old-School Wayundefinedfunction greet() {
if (true) {
var name = "John";
}
console.log(name); // ✅ Works
}
var a = 5;
var a = 10; // ✅ OK
let — The Modern Wayfunction greet() {
if (true) {
let name = "Alice";
console.log(name); // ✅ Works
}
// console.log(name); ❌ Error
}
let x = 5;
x = 10; // ✅ OK
let x = 20; // ❌ Error
const — Constant Valueconst pi = 3.14;
console.log(pi); // ✅
// pi = 3.14159; ❌ Error
const arr = [1, 2, 3];
arr.push(4); // ✅
const person = { name: "Bob" };
person.name = "Tom"; // ✅
You can't reassign arr or person, but you can modify their content.
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Re-declarable | ✅ Yes | ❌ No | ❌ No |
| Re-assignable | ✅ Yes | ✅ Yes | ❌ No |
| Hoisting | ✅ (undefined) | ✅ (but not initialized) | ✅ (but not initialized) |
Imagine a school:
var — A student known across the entire school (function)let — A student known only in their class group (block)const — A student with a fixed seat, but they can still open/change their notebook (content)let when the value might change.const for constants and object references.var unless maintaining old code.