let / const vs var
Understanding variable declarations is fundamental to JavaScript. ES2015 introducedlet andconst to fix the scoping, hoisting, and closure pitfalls ofvar.
What is the difference between let, const and var?
let and const are block-scoped (they only exist inside the nearest { }) and can't be used before their declaration. const also can't be reassigned. var is function-scoped, hoisted as undefined, can be redeclared, and leaks out of if and for blocks. Modern code uses const by default, let when reassigning, and never var.
if (true) {
var a = 1;
let b = 2;
}
a; // 1 (var leaked out of the block)
b; // ReferenceError
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2Quick Comparison
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function / Global | Block | Block |
| Hoisted | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Re-declaration | Allowed | Not allowed | Not allowed |
| Re-assignment | Allowed | Allowed | Not allowed |
| Global object property | Yes (in browser) | No | No |
| Use in for loop | Shared binding (bug) | New binding per iter | New binding per iter |
Temporal Dead Zone (TDZ)
let and const are hoisted to the top of their block but not initialized. Accessing them before their declaration throws a ReferenceError.
const is Not Deeply Immutable
const prevents re-assigning the binding, but the object it points to is still mutable. Use Object.freeze() for shallow immutability.
Best Practices
Use const for everything. It communicates intent and prevents accidental re-assignment.
Use let only when you genuinely need to re-assign (loop counters, accumulators, state machines).
var's function scope and hoisting behaviour lead to subtle bugs. Use let/const exclusively.
Even though TDZ applies, declaring early makes the code easier to reason about.
Common Pitfalls
Interactive Examples
Code Editor
<button id="run">Run</button>
<pre id="out"></pre>Preview
let, const, and var — step by step
var — function scoped and hoisted
var is scoped to the enclosing function (or global if outside any function). It is hoisted to the top of its scope and initialized to undefined — meaning you can reference it before the declaration without a ReferenceError, you just get undefined. Avoid var in modern code: block scope is almost always what you actually want.
🎯 Quick Check
What happens if you access a let variable before its declaration in the same scope?
let vs const vs var: summary
Key points
constobjects and arrays can still be modified; only the binding is constant.- Top-level
varcreates a property onwindow;letandconstdon't. - Redeclaring a
letin the same scope is a syntax error, which catches typos early.
Frequently asked questions
›Why does the var loop print 3 3 3?
var i is one shared variable for the whole function. By the time the callbacks run, the loop has finished and i is 3. let creates a new j for each iteration.