Var, Let and Const Compared

Updated · 8 min read
mediumES2026javascriptvarletconstinterview

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 as undefined, can be redeclared. Don't use it in new code.
  • var in a loop shares one variable across all rounds; let gives each round its own.
  • None of them make objects immutable; const only fixes the binding.

The Comparison Table

Featurevarletconst
ScopeFunctionBlockBlock
HoistedYes, as undefinedYes, uninitialized (TDZ)Yes, uninitialized (TDZ)
Use before declarationundefinedReferenceErrorReferenceError
Redeclare in the same scopeAllowedSyntaxErrorSyntaxError
ReassignAllowedAllowedTypeError
Must be initializedNoNoYes
Top level of a script creates a window propertyYesNoNo
New binding per loop roundNoYesYes (in for...of)
Introduced1995ES2015ES2015

Scope

scope.js▶ Try it
function demo() {
  if (true) {
    var fnScoped = "var";
    let blockScoped = "let";
    const alsoBlock = "const";
  }
  console.log(fnScoped);
  console.log(typeof blockScoped, typeof alsoBlock);
}
demo();
Output
var
undefined undefined

var ignores the if block and belongs to the whole function. let and const disappear when their block ends.

Redeclaration

redeclare.js▶ Try it
var total = 100;
var total = 200;
console.log(total);
Output
200

With 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

reassign.js▶ Try it
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);
Output
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:

loop-let.js▶ Try it
const reminders = [];
for (let i = 1; i <= 3; i++) {
  reminders.push(() => `Reminder ${i}`);
}
console.log(reminders.map((r) => r()));
Output
['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:

loop-iife.js▶ Try it
const reminders = [];
for (var i = 1; i <= 3; i++) {
  (function (n) {
    reminders.push(() => `Reminder ${n}`);
  })(i);
}
console.log(reminders.map((r) => r()));
Output
['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:

global.js
// 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:

  1. const by default. Most variables never need reassignment.
  2. let when you reassign: counters, running totals, values updated in a loop.
  3. Never var in new code. ESLint's no-var rule 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:

modern.js▶ Try it
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 }]));
Output
Navika: total $180, average $90

Common 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.

practice.js
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
practice-solution.js▶ Try it
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 }]));
Output
['Tuition: $400', 'Books: $85', 'Total: $485']

Quick check: var, let and const

3 questions
1Which declaration is function-scoped?
2What does declaring let x twice in the same scope do?
3Why do loops that create callbacks need let?

Key Takeaways

QuestionAnswer
Default choiceconst
Value changeslet
Reading old codeExpect var, function scope, hoisting as undefined
Loop with callbackslet i or for (const x of ...)

Was this tutorial helpful?

Lesson 44 of 139