Coding

var vs let vs const in JavaScript: Scope, Hoisting and Which to Use

Use const by default, let when the variable must be reassigned, and avoid var in new code. The difference is scope: var is scoped to the whole function and can be read before its declaration as undefined, while let and const are scoped to the nearest { } block and throw an error if used too early.

var vs let vs const at a glance

varletconst
ScopeFunction (or module/global)BlockBlock
Read before declarationundefinedReferenceErrorReferenceError
Redeclare in same scopeAllowedSyntaxErrorSyntaxError
ReassignAllowedAllowedTypeError
Must initialiseNoNoYes
Top-level script creates globalThis propertyYesNoNo
Loop closuresOne shared variableNew binding per iterationNew binding per iteration (for...of / for...in)

Every error message quoted below is the real output of Node.js 18; other engines word them slightly differently. You can paste the snippets into a browser console or a file run with node to check.

Scope: function vs block

A var belongs to the nearest enclosing function. Blocks such as if, for, try and switch do not contain it. A let or const belongs to the nearest pair of curly braces.

if (true) {
  var v = "visible";
  let l = "hidden";
}
console.log(v);         // "visible"
console.log(typeof l);  // "undefined" (l does not exist out here)

That leak is the main practical problem with var. A temporary variable declared inside an if can silently overwrite a variable with the same name elsewhere in the function. With let, an inner block can even reuse the name safely, because it is a separate variable:

let x = 1;
{
  let x = 2;          // different variable
  console.log(x);     // 2
}
console.log(x);       // 1

Hoisting and the temporal dead zone

All three declarations are processed before the code in their scope runs. The difference is what the variable holds before its line executes.

var is initialised to undefined, so reading it early quietly returns undefined:

function demo() {
  console.log(bar);   // undefined
  var bar = 111;
  console.log(bar);   // 111
}

let and const are uninitialised until their declaration runs. The stretch from the start of the block to that line is the temporal dead zone, and touching the variable there throws:

console.log(t);
let t = 1;

Output:

ReferenceError: Cannot access 't' before initialization

Even typeof t throws inside the dead zone, although typeof on a name that was never declared anywhere returns "undefined". The error is the point: a bug that var would hide as an undefined value shows up immediately.

Redeclaring a variable

var lets you declare the same name twice in one scope, even in strict mode. A redeclaration without a value keeps the old value:

var a = 1;
var a = 2;   // fine, a is 2
var a;       // still 2

let and const refuse, and so does mixing them with var, function or class of the same name in the same scope:

let a;
let a;
// SyntaxError: Identifier 'a' has already been declared

Because it is a SyntaxError, the whole script fails to load, not just that line. One place this bites: all case clauses of a switch share one block, so two cases that each declare let result collide. Wrap each case body in its own braces.

const: no reassignment, but the value can change

const needs a value on the same line, and the variable can never be pointed at something else:

const k;
// SyntaxError: Missing initializer in const declaration

const limit = 7;
limit = 20;
// TypeError: Assignment to constant variable.

What const fixes is the binding, not the value. Objects and arrays held in a const stay mutable:

const arr = [1];
arr.push(2);          // fine: [1, 2]
arr = [3];            // TypeError: Assignment to constant variable.

const config = { debug: false };
config.debug = true;  // fine

If you need the object itself locked, use Object.freeze(config). Writes to a frozen object are ignored in sloppy mode and throw a TypeError in strict mode. Freezing is shallow: an object nested inside is still writable.

The classic loop bug: var vs let in a for loop

This is the difference most likely to cause a real bug. Functions created inside a loop capture the loop variable. With var, there is one variable for the whole loop, so every function sees its final value. With let, each iteration gets its own copy.

var fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map(f => f()));   // [ 3, 3, 3 ]

let fns2 = [];
for (let j = 0; j < 3; j++) fns2.push(() => j);
console.log(fns2.map(f => f()));  // [ 0, 1, 2 ]

The same thing happens with setTimeout callbacks and event handlers attached in a loop. Changing var to let fixes all of them.

You cannot use const as the counter in a classic for (...; ...; i++) loop, because i++ reassigns it. In for (const item of items) it works, because each iteration creates a fresh binding rather than reassigning one.

Global variables: var adds a property to window

At the top level of a classic script, var creates a property on the global object (window in browsers, globalThis everywhere). let and const create a global variable that is not a property:

var gv = 1;
let gl = 2;
console.log(globalThis.gv, globalThis.gl);   // 1 undefined

That matters because a top-level var can collide with an existing window property or with another script on the same page. In ES modules (<script type="module">, .mjs files) and CommonJS files, top-level declarations of all three kinds are scoped to the module and never touch the global object.

Which one should you use?

  1. Start with const. Most variables are assigned once, and const tells the next reader so.
  2. Change it to let when you actually reassign it: counters, accumulators, a value set in one branch of an if.
  3. Leave var for code that must run in engines too old to support let and const, or for existing code you are not otherwise touching.

When converting old code, a blind find-and-replace of var with let is usually safe but not always. It breaks code that reads a variable before its declaration, code that redeclares the same name, and code that relies on a variable declared inside a block being visible after it. ESLint's no-var rule finds every var, and its --fix option rewrites the cases it can prove are safe and leaves the rest for you to review.

Comparisons have a similar old-versus-new split in JavaScript; see == vs === in JavaScript.

Frequently asked questions

Is var deprecated in JavaScript?
No. var is still part of the language and every engine supports it, so old code keeps working. It is simply discouraged in new code because block-scoped let and const avoid a class of bugs. Linters such as ESLint flag it with the no-var rule, which can rewrite many cases automatically with --fix.
Does const make an object immutable?
No. const only stops the variable from being pointed at a different value. The object or array it refers to can still change: properties can be added, changed or deleted and arrays can be pushed to. To stop changes to an object's own properties, use Object.freeze(), which is shallow: nested objects stay mutable.
Are let and const hoisted?
Yes, in the sense that the engine knows about them from the start of their block. Unlike var, they are not initialised to undefined. Reading them before the declaration line runs throws ReferenceError: Cannot access 'x' before initialization. That window is called the temporal dead zone.
Is const faster than let?
Do not choose between them for speed. The reason to prefer const is readability: a reader knows the binding never changes, and reassignment mistakes become an immediate TypeError instead of a silent bug.

Sources