Basics
Variables let and const
Two ways to declare a variable: const won't be reassigned, let will.
Why it exists
A variable is a name for a value: instead of 1200 * 3 you write price * count, and the code explains itself. Choosing between let and const is a hint to the reader (and protection from yourself): const promises the name always points to the same thing, and if you accidentally try to reassign it, JavaScript stops you with an error. When you see let, you know right away the value will change — it's a counter or an accumulator.
Where it's used
const— almost everything: settings, computed results, functions, arrays and objects.let— counters and accumulators:let count = 0,let total = 0,let result = "".let— values chosen by a condition:let message; if (…) message = ….- A loop counter
for (let i = 0; …)— it changes on every step.
Syntax
const name = value;
let name = value;Examples
let total = 0;
total = total + 5;
total; // → 5
const limit = 10;
// limit = 20; — TypeError: can't reassign
const list = [];
list.push(1);
list; // → [1] — the contents can changeconst prices = [300, 150, 50];
let total = 0;
for (const price of prices) {
total += price;
}
total; // → 500let for the accumulator, const for everything elseconst user = { name: "Ann" };
user.name = "Ann K.";
user; // → { name: "Ann K." }const doesn't stop you changing an object's propertieslet message;
const age = 20;
if (age >= 18) {
message = "Welcome";
} else {
message = "Adults only";
}
message; // → "Welcome"letResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
const forbids reassigning the variable, but it doesn't freeze the value. If a const holds an array or object, you can change its contents (push, a new property) — the variable still points to the same array.
Both kinds are visible only inside the block { … } where they're declared: a variable from a loop or an if doesn't exist outside it. This protects against accidental name clashes.
Before 2015 there was only var: it's visible in the whole function rather than the block, and lets you declare the same name twice. That caused hard-to-find bugs, so today var isn't used.
A rule from practice: write const by default and switch to let only when the variable really needs reassigning.
Traps
When to pick something else
Don't use var — it's the outdated way with confusing visibility rules. And don't reach for let "just in case": if a variable isn't reassigned, make it const.
Practice
Lessons where this appears
- Byte clears out the atticTale · Chapter 1 · Variables and types
- The Null GhostBoss · Chapter 1 · Variables and types
- Byte's sock empireTale · Chapter 5 · Arrays and loops
- Largest numberLab · Chapter 5 · Arrays and loops
- Why can't you fix a string?Why? · Chapter 6 · Strings
- A passport for a catTale · Chapter 8 · Objects