Choosing between let, const, and var is the first real style decision that you make in JavaScript. Most of the confusion around it comes from three myths. The first myth says that const makes a value impossible to change. The second says that var and let differ only in timing. The third says that var is somehow the flexible one. This lesson shows what each keyword actually does to your program.
This is the first lesson in the JavaScript Variables and Data Types module, and the next lesson in this module is about "Numbers in JavaScript: Integers, Floats, BigInt".
What is the real difference between the three keywords?
A variable in JavaScript is a binding, which is a name attached to a value. The keyword that you choose decides whether that name can be pointed at a different value later on. It does not decide what the value itself is, and it does not decide how the value behaves.
| Keyword | Can be reassigned? | Scope | Still worth using? |
|---|---|---|---|
const | No | Block | Yes, and it should be your default |
let | Yes | Block | Yes, when the value really has to change |
var | Yes | Function | Almost never |
That is the whole distinction. Everything else, including hoisting, the temporal dead zone, and the famous loop bug, follows from how the binding behaves.
Does const make a value immutable?
No, and this is the myth that causes the most confusion. const freezes the binding and not the value. If the value is an object or an array, you are still free to change what is inside it.
const settings = { theme: "light", notifications: true };
// This is allowed. The object was changed, not the binding.
settings.theme = "dark";
console.log("after mutation:", settings.theme);
try {
settings = { theme: "solar" };
} catch (error) {
console.log("caught:", error.constructor.name, "-", error.message);
}
Run that and it prints after mutation: dark and then caught: TypeError - Assignment to constant variable. If you want a value that really cannot change, you need a frozen object, and that is a different tool with different trade-offs.
Why was var retired?
There are three reasons, and each one has bitten somebody.
The first reason is that var is function-scoped and not block-scoped. A var declared inside an if block or a for block stays visible for the whole enclosing function, which means that a name that was meant for one branch leaks into every other branch.
function withVar() {
if (true) {
var leaked = "declared with var";
}
// This works, because var is function-scoped.
return leaked;
}
function withLet() {
if (true) {
let scoped = "declared with let";
}
// This throws a ReferenceError, because let is block-scoped.
return scoped;
}
console.log("var:", withVar());
try {
withLet();
} catch (error) {
console.log("let:", error.constructor.name, "-", error.message);
}
The second reason is that a var inside a loop shares one binding across every round of the loop, so all of the functions that you create in that loop end up seeing the final value. A let creates a fresh binding for each round.
// With var, every function shares one variable.
const varCallbacks = [];
for (var i = 0; i < 3; i += 1) {
varCallbacks.push(function () { return i; });
}
console.log("var results:", varCallbacks.map(function (fn) { return fn(); }));
// With let, each round gets its own variable.
const letCallbacks = [];
for (let j = 0; j < 3; j += 1) {
letCallbacks.push(function () { return j; });
}
console.log("let results:", letCallbacks.map(function (fn) { return fn(); }));
The output is the clue. The var version prints [ 3, 3, 3 ] and the let version prints [ 0, 1, 2 ]. The first one printed 3 three times because all three functions point at the same i, and that variable had reached 3 when the loop ended. The second one printed 0, 1, and 2 because each round captured its own copy of the number.
The third reason is that a var at the top level of a script becomes a property of the global object, so it can collide with another script on the same page. A top-level let or const does not do that.
What is the temporal dead zone?
Both var and let are hoisted, which means that the engine knows about the binding before your code reaches it. What differs is the state of the binding at that moment. A hoisted var already exists and holds undefined. A hoisted let exists but is not initialised yet, and touching it inside that window is an error. That window is called the temporal dead zone.
// This prints undefined instead of causing an error.
console.log("var value:", hoistedVar);
var hoistedVar = "assigned later";
try {
console.log("let value:", hoistedLet);
} catch (error) {
console.log("let before init:", error.constructor.name, "-", error.message);
}
let hoistedLet = "assigned later";
The first line prints var value: undefined. The second one throws a ReferenceError with the message Cannot access 'hoistedLet' before initialization. This is why calling a function before its const declaration fails, while calling a function declaration before its definition works. The two use the keywords in different ways, and function declarations are covered in detail later in this module.
Which keyword should I actually use?
Here is a simple rule that you can defend: declare with const by default, switch to let only when the binding really has to change, and do not write new var at all.
const MAX_RETRIES = 3;
let attempts = 0;
while (attempts < MAX_RETRIES) {
attempts += 1;
console.log("attempt " + attempts + " of " + MAX_RETRIES);
}
You get three attempts and three log lines, and a reader can tell from the declaration alone which values are fixed and which ones move. That single glance is worth more than any amount of extra documentation.
There is one nuance worth keeping in mind. const does not make a value immutable, it makes the name stable. A const that holds a large object is still changeable underneath, so const is a statement of intent about the binding and not a guarantee about the data. If you want the data itself to be frozen, say so explicitly with Object.freeze, and accept that it is a shallow freeze.
How do I convert old var code safely?
Most of the code that you will read online still uses var, because it was the only option for the first fifteen years of the language. Converting it is usually mechanical. You change the keyword and you run the tests. There is one exception that you have to check by hand, and that is any name that was declared inside a block and then read outside it, because that is exactly the case that let will break.
// Before: the name exists outside the block and reads as undefined.
function surcharge(orders) {
if (orders.length > 0) {
var hasOrders = true;
}
return hasOrders ? 10 : 0;
}
console.log("with orders:", surcharge([1]));
console.log("no orders:", surcharge([]));
After you change that var to let, the second call throws a ReferenceError, because hasOrders no longer exists outside the block. The fix is to move the read inside the block, where the name is still in scope.
// After: the binding stays inside the block, so read it there.
function surcharge(orders) {
if (orders.length > 0) {
let hasOrders = true;
return hasOrders ? 10 : 0;
}
return 0;
}
console.log("with orders:", surcharge([1]));
console.log("no orders:", surcharge([]));
The two versions print the same two lines, but the second one no longer depends on a variable that happened to hold undefined. That is the pattern to look for when you convert old code. A name that is read outside the block that declared it was always a bug waiting for the right input.
The three rules to remember
conststops the name from being pointed at something else. It does not freeze the value.letandconstare block-scoped, whilevaris function-scoped and leaks out of blocks.letandconstlive in a temporal dead zone until their declaration runs, whilevarstarts life asundefined.- Default to
const, useletfor genuine change, and avoidvarexcept in code that you are maintaining rather than writing.
Try it yourself: take any script that you have written so far and change every var to let. Most of them will keep working, which proves that the two are often interchangeable in simple code. Then find a var that is declared inside an if block and read after that block, and watch the let version throw a ReferenceError where the var version quietly worked. That crash is the bug that var was hiding.