Var, Let & Const in JavaScript: Explained Simply
JavaScript gives you three ways to declare a variable. Most bugs in this space come from picking the wrong one. Here's the short version, then the why.
The short version
Default to
const. Useletonly when you actually need to reassign. Never usevar.
That's it. The rest of this post is why.
Var: function-scoped, hoisted, dangerous
var declarations are scoped to the nearest function — not the nearest block. This means:
function example() {
if (true) {
var x = 1;
}
console.log(x); // 1 — yes, really
}
This isn't a bug. It's how JavaScript was designed in 1995. And it's the source of countless subtle issues.
Let: block-scoped, predictable
let fixes the scoping problem:
function example() {
if (true) {
let x = 1;
}
console.log(x); // ReferenceError — x is not defined here
}
let exists where you'd expect, and nowhere else.
Const: block-scoped, immutable binding
const is let plus a guarantee: you can't reassign it.
const user = { name: "Abdul" };
user.name = "Rehman"; // ✅ allowed — object's contents can change
user = { name: "Other" }; // ❌ TypeError — the binding can't be reassigned
The thing being constant is the binding, not the value.
The one rule that prevents 90% of declaration bugs
Use const until the linter tells you otherwise.
When you try to reassign and the linter flags it, switch to let. You'll find that 80%+ of variables never need to be let — they're set once and used. That's a feature, not a limitation: code where most values don't change is easier to reason about.
TL;DR
| Keyword | Scope |
|---|
2 comments
Const-by-default rule is the cleanest mental model I've seen. Linking to onboarding docs.
test