What is the difference between var, let, and const?

var is function-scoped and can be redeclared; let and const are block-scoped, live in the temporal dead zone until declared, and const cannot be reassigned.

varletconst
ScopeFunctionBlock {}Block {}
HoistedYes, initialised to undefinedYes, but uninitialised (TDZ)Yes, but uninitialised (TDZ)
Redeclare in same scopeAllowedErrorError
ReassignAllowedAllowedError
Creates global object propertyYes (window.x)NoNo

What const really means

const freezes the binding, not the value. A const array or object can still be mutated. Use Object.freeze if you need the value itself to be read-only.

The classic loop bug

With var, every callback in a loop shares one variable, so they all see the final value. let creates a fresh binding per iteration, which is why the bug disappears.

Best practice

Default to const, use let only when you reassign, and avoid var in modern code. This makes intent obvious and lets linters catch accidental reassignment.

Code example

js
1// Scope
2function demo() {
3 if (true) {
4 var a = "function scoped";
5 let b = "block scoped";
6 }
7 console.log(a); // "function scoped"
8 console.log(typeof b); // "undefined" (b does not exist here)
9}
10demo();
11
12// const freezes the binding, not the value
13const list = [1, 2];
14list.push(3); // fine
15console.log(list); // [1, 2, 3]
16try {
17 list = []; // TypeError: Assignment to constant variable
18} catch (e) {
19 console.log(e.constructor.name); // TypeError
20}
21
22// var vs let in loops with async callbacks
23for (var i = 0; i < 3; i++) setTimeout(() => console.log("var:", i)); // 3, 3, 3
24for (let j = 0; j < 3; j++) setTimeout(() => console.log("let:", j)); // 0, 1, 2

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app