The short answer
In modern JavaScript, start with const. Use let when the variable has to change later, such as a counter. New code rarely needs var.
What const and let do
Both const and let are block scoped, so each one exists only inside the nearest { } block. The difference is reassignment. let allows a new value, and const doesn’t:
let count = 0;
count = count + 1; // OK
const limit = 10;
limit = 20; // TypeError: Assignment to constant variable.
When const is the right default
Use const when the name should keep pointing at the same value for its whole life. That covers most variables in a typical program:
const price = 19.99;
const user = { name: "Ana", age: 30 };
user.age = 31; // OK: the object changes, but the name still points to it
Arrays and objects work the same way. You can change their contents with const, but you can’t point the name at a different array or object.
const also works well in loops that go through each item without changing the name:
const items = ["pen", "cup", "book"];
for (const item of items) {
console.log(item);
}
When let makes sense
Use let when the value changes:
let total = 0;
for (let i = 0; i < 3; i++) {
total += i;
}
Here i changes on every pass, so it needs let. The same is true of total.
Sometimes a variable gets its value after a condition. You can write it with let, or often with const and a conditional expression:
const score = 72;
const label = score > 50 ? "pass" : "retry";
Why avoid var in new code
var is function scoped and hoisted, and it allows the same name to be declared twice. Those features cause surprises that let and const avoid. Many popular JavaScript style guides recommend const by default, let when reassignment is needed, and no var at all. For a side-by-side comparison of the two older and newer keywords, see what is const vs var?
A quick rule
- Start with
const. - If the code needs to reassign the name, switch to
let. - Don’t use
varin new code.
For readers coming from C++
In C++, const on an object protects its contents through that name. That’s stricter than JavaScript’s const, which only stops reassignment of the name, as the rule above describes. In C++ the question of whether a value can change is handled by const itself, and auto only deduces a type. You can combine them, as in const auto total = compute();, when you want a type deduced and a value that can’t change. The C++ rules are covered in the c const keyword guide.