The short answer
#Use const for everything by default, switch to let only when you need to reassign the variable, and do not use var in new code. const and let are block scoped and fail loudly when misused, while var is function scoped and has quirks that cause real bugs.
_10const apiUrl = "https://api.example.com"; // never reassigned_10let retries = 0; // reassigned below_10_10while (retries < 3) {_10 retries += 1;_10}
Why it happens
#var is the original way to declare variables. let and const arrived in ES2015 to fix its problems. There are three differences that matter.
Scope
var is scoped to the nearest function. let and const are scoped to the nearest block, which is any pair of curly braces: an if, a loop, or a bare block.
_10if (true) {_10 var a = 1;_10 let b = 2;_10}_10_10console.log(a); // 1, because var leaks out of the block_10console.log(b); // ReferenceError: b is not defined
Hoisting and the temporal dead zone
All three declarations are hoisted to the top of their scope, but they behave differently before the line that declares them. A var exists and holds undefined. A let or const exists but cannot be touched until its declaration runs. That gap is called the temporal dead zone.
_10console.log(count); // undefined, a silent bug_10var count = 5;_10_10console.log(total); // ReferenceError: Cannot access 'total' before initialization_10let total = 5;
The error is the better outcome. It points straight at the problem instead of letting undefined travel through your code.
Reassignment and redeclaration
const cannot be reassigned. let can. Neither can be declared twice in the same scope, while var happily lets you redeclare a name and overwrite it without warning.
_10const limit = 10;_10limit = 20; // TypeError: Assignment to constant variable._10_10var name = "Ada";_10var name = "Grace"; // no error, the first value is gone
How to fix it
#Default to const
Most variables are assigned once. Declaring them with const tells the reader the binding will not change, so they can stop tracking it. If you later need to reassign it, the error tells you exactly where, and you change that one declaration to let.
_10const user = await getUser(id);_10const fullName = `${user.firstName} ${user.lastName}`;
Use let for counters, accumulators and flags
Reach for let when the value genuinely changes over time.
_10let total = 0;_10for (const item of cart) {_10 total += item.price * item.quantity;_10}
Notice that the loop variable is const. In a for...of loop each iteration gets a fresh binding, so const works. In a classic for (let i = 0; ...) loop you need let, because i is incremented.
Replace var in old code
When you touch legacy code, swapping var for let or const is usually safe, but check two cases first: code that reads the variable before its declaration, and code that relies on the variable being visible outside a block. Both will now throw, which is what you want to find out about.
ESLint can enforce all of this with the no-var and prefer-const rules.
Common pitfalls
#- const does not make values immutable. It stops you reassigning the variable, not changing the object it points to.
const settings = { theme: "dark" }still allowssettings.theme = "light". UseObject.freeze()if you need a shallow read-only object. - The classic loop and closure bug. With
var, every callback created in a loop shares one variable, so they all see its final value.letcreates a new binding per iteration.
_10for (var i = 0; i < 3; i++) {_10 setTimeout(() => console.log(i)); // 3, 3, 3_10}_10_10for (let j = 0; j < 3; j++) {_10 setTimeout(() => console.log(j)); // 0, 1, 2_10}
- Top-level var in a classic script creates a global property. A
varat the top of a non-module script becomes a property ofwindow.letandconstdo not, and in ES modules nothing at the top level is global. - switch cases share one block. Declaring the same
letname in twocaseclauses throws a SyntaxError. Wrap each case body in its own curly braces. - typeof is not safe in the temporal dead zone.
typeof xnormally returns"undefined"for unknown names, but throws ifxis aletorconstthat has not been initialised yet.
Related reading
#quick question
Was this resource helpful?
by Danny