Skip to content
jshacks.dev
Fundamentals

var vs let vs const in JavaScript and the Real Differences

var is function scoped and hoisted as undefined, while let and const are block scoped and blocked before their line. See the loop bug and what to use.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Node.js, npm, TypeScript and Vite logos.

The single most useful change you can make to old JavaScript is replacing var with const or let, and the reason is not style. It is a loop that prints the same number three times, a variable that is undefined instead of an error, and a name that quietly leaks out of an if block. Each of those is a consequence of how var is scoped and hoisted, and each disappears with the newer keywords. This post puts the three side by side with output from Node.js 24 and ES2026, shows the loop bug and the redeclaration rule, and ends on a rule for choosing. The scope vocabulary is in block scope versus function scope and the hoisting detail in the post on hoisting.

varletconst
ScopeFunctionBlockBlock
HoistedYes, initialized to undefinedYes, but unusable until its lineYes, but unusable until its line
Redeclare in the same scopeAllowedSyntaxErrorSyntaxError
ReassignAllowedAllowedTypeError
Creates a property on the global objectIn classic scripts, yesNoNo

The loop that prints the same number

The famous bug comes from a closure capturing a var that every iteration shares.

JavaScript
const withVar = [];
for (var i = 0; i < 3; i++) {
  withVar.push(() => i);
}

const withLet = [];
for (let j = 0; j < 3; j++) {
  withLet.push(() => j);
}

console.log(withVar.map((fn) => fn()));
console.log(withLet.map((fn) => fn()));
Text
[ 3, 3, 3 ]
[ 0, 1, 2 ]

There is one i for the whole loop, and by the time the closures run it holds 3. With let, the specification creates a new binding for each iteration and copies the value into it, so each closure keeps its own number. This is the example people remember, because the old fix was an immediately invoked function that captured i as an argument. Replacing var with let makes that workaround unnecessary. The post on scope, hoisting and closures goes deeper on why the closure keeps the variable alive.

Reading before the declaration

A var is hoisted to the top of its function and starts as undefined, so reading it early gives undefined and no complaint. A let or const exists from the start of its block but cannot be touched until its declaration runs, a region called the temporal dead zone.

JavaScript
console.log(early);
var early = "set";

try {
  console.log(later);
} catch (error) {
  console.log(error.name, error.message);
}
let later = "set";

console.log(typeof neverDeclared);
Text
undefined
ReferenceError Cannot access 'later' before initialization
undefined

The first line prints undefined, which is the bug-friendly behavior: a statement written in the wrong order gives a wrong value and no error. The second throws, which turns the same mistake into a loud failure at the exact line. typeof on a name that was never declared is the one probe that does not throw, and the post on the temporal dead zone explains why the dead zone exists at all.

Block scope and the leaking var

let and const stop at the nearest braces. A var declared inside an if, a for or a plain block is visible in the whole function.

JavaScript
function describe(flag) {
  if (flag) {
    var leaked = "from var";
    let contained = "from let";
  }

  console.log(leaked);
  console.log(typeof contained);
}

describe(true);
describe(false);
Text
from var
undefined
undefined
undefined

When the branch ran, leaked is available after the block, and contained does not exist outside it. When the branch did not run, leaked is still declared, because of hoisting, and holds undefined. That last behavior is why a var inside a conditional is a trap: the name is always there and sometimes empty.

Redeclaration

var lets you declare the same name twice in one scope, which hides a copy and paste mistake. The other two refuse.

JavaScript
var count = 1;
var count = 2;
console.log(count);

try {
  eval("let total = 1; let total = 2;");
} catch (error) {
  console.log(error.name, error.message);
}
Text
2
SyntaxError Identifier 'total' has already been declared

The first block is legal and silently overwrites the first value. The second is rejected at parse time, which the example reaches through eval so it can be caught. In a real file, the whole script fails to load with a SyntaxError, which is better than a bug that runs.

What const does and does not do

const fixes the binding, the link between the name and the value. It does not make the value immutable.

JavaScript
const settings = { theme: "light", tags: ["a"] };

settings.theme = "dark";
settings.tags.push("b");
console.log(settings);

try {
  settings = {};
} catch (error) {
  console.log(error.name, error.message);
}
Text
{ theme: 'dark', tags: [ 'a', 'b' ] }
TypeError Assignment to constant variable.

The object changed freely, and reassigning the name threw. Object.freeze() goes further, and its limits are worth seeing.

JavaScript
const frozen = Object.freeze({ theme: "light", tags: ["a"] });

try {
  frozen.theme = "dark";
} catch (error) {
  console.log(error.name, error.message);
}

frozen.tags.push("b");
console.log(frozen);
Text
TypeError Cannot assign to read only property 'theme' of object '#<Object>'
{ theme: 'light', tags: [ 'a', 'b' ] }

The top-level write threw a TypeError, because ES modules run in strict mode (in sloppy mode the write is silently ignored), and the nested array stayed editable because the freeze is shallow. The post on primitives versus objects explains why a reference can be constant while its target is not.

A for loop counter cannot be const, because it is reassigned each pass, though a for...of loop can use it, since each iteration has a fresh binding.

JavaScript
for (const word of ["a", "b"]) {
  console.log(word);
}

try {
  for (const n = 0; n < 2; n++) {
    console.log(n);
  }
} catch (error) {
  console.log(error.name, error.message);
}
Text
a
b
0
TypeError Assignment to constant variable.

The counting loop printed 0 and then failed on the increment, which is the pattern to remember: a const in the first clause survives one pass.

The global object

In a classic script, a top-level var becomes a property of the global object, and a let does not. In an ES module or a CommonJS file the top level is module scope, so neither leaks.

JavaScript
var topLevelVar = 1;
let topLevelLet = 2;

console.log(globalThis.topLevelVar);
console.log(globalThis.topLevelLet);
Text
undefined
undefined

Both print undefined here because this file runs as a module. In a browser <script> without type="module", the first would print 1, and that is how var once caused collisions between unrelated scripts on one page. The post on globalThis covers the global object.

A rule for choosing

Start every binding as const. Change it to let the first time the code needs to reassign it, and not before. Do not write var. That rule is easy to state, easy to review and enforceable.

JavaScript
// eslint.config.js
export default [
  {
    rules: {
      "no-var": "error",
      "prefer-const": "error",
    },
  },
];

no-var rejects the old keyword and prefer-const flags a let that is never reassigned. Together they make the choice automatic, and most of the diff when you adopt them is mechanical. We apply them in one commit with the auto-fixer, and review the handful of var declarations that the fixer refuses to change, because those are the ones that rely on hoisting or redeclaration.

The reason to start with const is information. A reader who sees const knows the name never points anywhere else, and can stop tracking it. A reader who sees let has to scan the function for reassignments. Over a file of two hundred lines, that difference adds up, and it is the main benefit of the habit, ahead of any bug it prevents.

Migrating a file safely

Moving a file off var is safe when you go in order. First, run prefer-const and no-var with the fixer, and read the diff, since it will turn every var that is never reassigned into const. Second, look at each remaining var and ask whether any code reads it outside the block where it was declared, or before its line. Those are the cases where the conversion changes behavior, and the tests should cover them. Third, search for loops whose variable is used after the loop ends, such as a search that stops at an index and then reads i. Those need a let declared before the loop.

If a conversion produces a ReferenceError that you did not expect, the code was reading a var before its declaration and getting undefined. That is a real bug that the old keyword had been hiding, and it deserves a fix and not a revert.

Where var still appears

Old code is the main place, and rewriting it blindly changes behavior wherever it relied on hoisting, on a loop variable read after the loop or on a redeclaration. Convert file by file and run the tests between files. Generated and transpiled output uses var on purpose, and you should leave it alone.

A second case is a deliberate function-level variable in a very large function, where var communicates "visible everywhere in here". A better fix is a smaller function, and let declared at the top does the same.

The rules are defined in the specification under let and const declarations and variable statements, and MDN's pages on let, const and var list the differences.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.