If you look at old JavaScript code, you'll see var everywhere. Look at anything written in the last several years, and you'll barely see it at all. There's a real reason for that shift, and it's worth understanding rather than just memorising "use let and const."
The modern default: let and const
let age = 25;
age = 26; // fine, let can be reassigned
const name = "Sam";
name = "Alex"; // error! const can't be reassignedconst means the variable can't be reassigned after it's set. Reach for it by default, always. Only switch to let when you genuinely know the value will need to change later, like a counter going up in a loop. This habit alone catches a surprising number of bugs, because you get an error the moment you accidentally try to overwrite something that shouldn't change.
So what is wrong with var?
var has a scoping rule that trips people up constantly: it doesn't respect block boundaries the way let and const do. Take a look:
if (true) {
var x = 10;
}
console.log(x); // 10 — leaked out of the if block!
if (true) {
let y = 10;
}
console.log(y); // error — y doesn't exist out hereWith var, x escapes the if block entirely and is still visible outside it, which is almost never what you actually want, and it gets genuinely confusing in bigger programs with nested blocks everywhere. let and const fix this by respecting the curly braces you can actually see on screen, which lines up with how most people naturally read code.
const doesn't mean "frozen," by the way
const person = { name: "Sam" };
person.name = "Alex"; // this is totally fine
person = {}; // this isn't — reassigning the variable itselfThis one genuinely surprises people the first time. const only locks the variable name to a particular object or array — it says nothing about whether the contents of that object can change. If you truly need an unchangeable object, that's a separate topic (Object.freeze), but don't assume const gives you that for free.
The rule of thumb
Use const unless you've a specific reason to reassign the variable, in which case use let. There's essentially no good reason to reach for var in code you're writing today — it mostly exists now for compatibility with old code that hasn't been updated yet.