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.
var | let | const | |
|---|---|---|---|
| Scope | Function | Block {} | Block {} |
| Hoisted | Yes, initialised to undefined | Yes, but uninitialised (TDZ) | Yes, but uninitialised (TDZ) |
| Redeclare in same scope | Allowed | Error | Error |
| Reassign | Allowed | Allowed | Error |
| Creates global object property | Yes (window.x) | No | No |
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
1// Scope2function 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();1112// const freezes the binding, not the value13const list = [1, 2];14list.push(3); // fine15console.log(list); // [1, 2, 3]16try {17 list = []; // TypeError: Assignment to constant variable18} catch (e) {19 console.log(e.constructor.name); // TypeError20}2122// var vs let in loops with async callbacks23for (var i = 0; i < 3; i++) setTimeout(() => console.log("var:", i)); // 3, 3, 324for (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.