Var, Let and Const Compared
JavaScript has three keywords for declaring variables: var (the original, from 1995), and let and const (added in ES2015). They differ in scope, hoisting, whether they can be redeclared or reassigned, and how they interact with the global object. This lesson puts every difference side by side, shows the classic bug that made var obsolete, and ends with the simple rule modern teams follow.
In One Minute
const: block-scoped, can't be reassigned, must be initialized. Use it by default.let: block-scoped, can be reassigned. Use it when the value must change.var: function-scoped, hoisted asundefined, can be redeclared. Don't use it in new code.varin a loop shares one variable across all rounds;letgives each round its own.- None of them make objects immutable;
constonly fixes the binding.
The Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes, as undefined | Yes, uninitialized (TDZ) | Yes, uninitialized (TDZ) |
| Use before declaration | undefined | ReferenceError | ReferenceError |
| Redeclare in the same scope | Allowed | SyntaxError | SyntaxError |
| Reassign | Allowed | Allowed | TypeError |
| Must be initialized | No | No | Yes |
Top level of a script creates a window property | Yes | No | No |
| New binding per loop round | No | Yes | Yes (in for...of) |
| Introduced | 1995 | ES2015 | ES2015 |
Scope
function demo() {
if (true) {
var fnScoped = "var";
let blockScoped = "let";
const alsoBlock = "const";
}
console.log(fnScoped);
console.log(typeof blockScoped, typeof alsoBlock);
}
demo();var
undefined undefinedvar ignores the if block and belongs to the whole function. let and const disappear when their block ends.
Redeclaration
var total = 100;
var total = 200;
console.log(total);200With var, declaring the same name twice silently reuses the variable. In a long file, a second var total written by someone else can overwrite your value without any warning. With let or const, the same code is a SyntaxError before anything runs ("Identifier 'total' has already been declared"), so the mistake is caught immediately.
Reassignment
let balance = 450;
balance -= 200;
console.log(balance);
const fee = 450;
try {
fee = 500;
} catch (err) {
console.log(err.name + ": " + err.message);
}
const fees = [450];
fees.push(85);
console.log(fees);250
TypeError: Assignment to constant variable.
[450, 85]const stops the name from being pointed elsewhere, but the array it points to can still change.
The Loop Closure Bug
This is the bug that most clearly shows why let replaced var. Each round of the loop creates a function that remembers i, to run later:
const reminders = [];
for (let i = 1; i <= 3; i++) {
reminders.push(() => `Reminder ${i}`);
}
console.log(reminders.map((r) => r()));const reminders = [];
for (var i = 1; i <= 3; i++) {
reminders.push(() => `Reminder ${i}`);
}
console.log(reminders.map((r) => r()));
// ['Reminder 4', 'Reminder 4', 'Reminder 4']['Reminder 1', 'Reminder 2', 'Reminder 3']Explanation: with var, there is exactly one i for the whole function. All three functions refer to that one variable, and by the time they run, the loop has finished and i is 4. With let, the specification creates a fresh i for every round, copying in the current value, so each function remembers its own.
Before ES2015, the fix was to create a new scope per round with an immediately called function:
const reminders = [];
for (var i = 1; i <= 3; i++) {
(function (n) {
reminders.push(() => `Reminder ${n}`);
})(i);
}
console.log(reminders.map((r) => r()));['Reminder 1', 'Reminder 2', 'Reminder 3']You'll still meet this pattern in older code. With let, it is no longer needed.
The Global Object
In a classic script, a top-level var (and a top-level function declaration) becomes a property of the global object. A top-level let or const is global too, but not a property of window:
// In a classic <script> in a browser:
var appName = "Fee Tracker";
let version = 3;
console.log(window.appName); // "Fee Tracker"
console.log(window.version); // undefined
console.log(version); // 3: still a global variable, just not a window property
var name = "Navika"; // overwrites window.name, which browsers use for the tab's name!A var at the top level can collide with built-in browser properties such as name, status or top. This is another reason to avoid var, and to use modules, where top-level declarations aren't global at all. (The Try it runner wraps examples in a function, so this example is shown without running.)
Which to Use
Modern style guides (Airbnb, Google, StandardJS) and ESLint's recommended rules agree:
constby default. Most variables never need reassignment.letwhen you reassign: counters, running totals, values updated in a loop.- Never
varin new code. ESLint'sno-varrule enforces it.
Reading const tells you the name never changes. Reading let tells you to watch for reassignment. That is information var never gave.
In Practice
Older Fee Tracker code converted to modern declarations. Each var becomes const unless it is reassigned:
function summarize(payments) {
const owner = payments[0].name;
let total = 0;
for (const p of payments) {
total += p.amount;
}
const average = total / payments.length;
return `${owner}: total $${total}, average $${average}`;
}
console.log(summarize([{ name: "Navika", amount: 120 }, { name: "Navika", amount: 60 }]));function summarize(payments) {
var owner = payments[0].name;
var total = 0;
for (var i = 0; i < payments.length; i++) {
total += payments[i].amount;
}
var average = total / payments.length;
return owner + ": total $" + total + ", average $" + average;
}Navika: total $180, average $90Common Mistakes
Mechanically replacing every var with let. Usually right, but code that relied on var leaking out of a block (used after an if or loop) breaks. Move the declaration up to where it's needed.
Choosing let "in case it changes later". Start with const; change it to let the moment you need to reassign.
Thinking const objects are frozen. Their properties can change. Use Object.freeze for that.
Using var in loops that create callbacks. The shared variable bug. Use let.
Interview Corner
Explain the differences between var, let and const.
var is function-scoped, hoisted and initialized to undefined, can be redeclared, and at the top level of a script creates a global object property. let and const are block-scoped, hoisted but uninitialized (temporal dead zone), can't be redeclared in the same scope, and don't create global object properties. const additionally can't be reassigned and must be initialized. let and const in loop heads create a new binding per iteration.
Why does a for loop with var and setTimeout print the final value?
All callbacks close over the single function-scoped var binding, which holds the final value when they run. let creates a fresh binding per iteration, so each closure captures its own value. The pre-ES2015 fix was an IIFE per iteration.
Practice
Challenge: Convert this function to use const and let appropriately (use const wherever possible) and make sure it still prints the same result.
function receiptLines(items) {
var lines = [];
var total = 0;
for (var i = 0; i < items.length; i++) {
var item = items[i];
total += item.price;
lines.push(item.name + ": $" + item.price);
}
lines.push("Total: $" + total);
return lines;
}Show solution
function receiptLines(items) {
const lines = [];
let total = 0;
for (const item of items) {
total += item.price;
lines.push(`${item.name}: $${item.price}`);
}
lines.push(`Total: $${total}`);
return lines;
}
console.log(receiptLines([{ name: "Tuition", price: 400 }, { name: "Books", price: 85 }]));['Tuition: $400', 'Books: $85', 'Total: $485']Key Takeaways
| Question | Answer |
|---|---|
| Default choice | const |
| Value changes | let |
| Reading old code | Expect var, function scope, hoisting as undefined |
| Loop with callbacks | let i or for (const x of ...) |
Was this tutorial helpful?