JavaScript const, let, Scope, and Hoisting
Lesson 1 of 38 in the JavaScript learning path.
How do const and let differ from var?
const and let are the block-scoped bindings to use in browser JavaScript. const refuses a later assignment to that name, while let allows one, which is what a counter or a selected lesson id needs. A read before the declaration line throws ReferenceError. That gap is the temporal dead zone, and it does not quietly return undefined the way var does. A const object or array can still be mutated, because the binding keeps the same object while a property or item changes.
var is function scoped, it is hoisted as undefined, and braces do not contain it. A var loop index is one shared binding, so every callback created in the loop sees the final number. Declare each name once, close to the first use, and prefer const until an assignment is real. Quiz timers, dashboard filters, and lesson widgets stay understandable when a block cannot leak a name into the rest of the function.
Syntax & Parameters
const name = value;
let counter = 0;
var leaked = "function scoped";
Example
Interactive preview available'use strict';
function blockReport() {
const course = 'Web Fundamentals';
let seatsLeft = 24;
var leaked = 'function-scoped';
let badgeSeen = false;
let students = [];
if (seatsLeft > 0) {
const badge = 'open';
const roster = { title: course, students: ['Amina'] };
roster.students.push('Ken');
students = roster.students.slice();
seatsLeft -= 1;
badgeSeen = badge === 'open';
var leaked = 'var reuses the function binding';
}
let badgeOutside = 'not declared here';
try { badgeOutside = badge; } catch (error) { badgeOutside = error.name; }
return { course, seatsLeft, badgeSeen, leaked, badgeOutside, students };
}
function readBeforeInit() {
const probe = () => topic;
let failure = 'none';
try { probe(); } catch (error) { failure = error.name; }
const topic = 'scope';
return failure;
}
function letCaptures() {
const reads = [];
for (let index = 0; index < 3; index += 1) reads.push(() => index);
return reads.map((read) => read());
}
function varCaptures() {
const reads = [];
for (var index = 0; index < 3; index += 1) reads.push(() => index);
return reads.map((read) => read());
}
function reassignmentVersusMutation() {
const config = { track: 'javascript', weeks: [1] };
config.weeks.push(2);
let mode = 'draft';
mode = 'published';
let reassignment = 'allowed';
try { config = { track: 'css' }; } catch (error) { reassignment = error.name; }
return { weeks: config.weeks.slice(), mode, reassignment };
}
const report = {
block: blockReport(),
beforeInit: readBeforeInit(),
letIndexes: letCaptures(),
varIndexes: varCaptures(),
binding: reassignmentVersusMutation(),
};
const output = document.getElementById('scope-output');
if (output !== null) {
output.textContent = JSON.stringify(report, null, 2);
}
console.log(JSON.stringify(report, null, 2));
Expected Output
Console and #scope-output:
{
"block": {
"course": "Web Fundamentals",
"seatsLeft": 23,
"badgeSeen": true,
"leaked": "var reuses the function binding",
"badgeOutside": "ReferenceError",
"students": ["Amina", "Ken"]
},
"beforeInit": "ReferenceError",
"letIndexes": [0, 1, 2],
"varIndexes": [3, 3, 3],
"binding": {
"weeks": [1, 2],
"mode": "published",
"reassignment": "TypeError"
}
}
Line-by-Line Walkthrough
- Strict mode is on, so an assignment to a name that was never declared throws, and the later const reassignment fails with TypeError.
- blockReport stores the course title in a const and the seat count in a let, then opens an if block that owns the badge const and the roster object.
- roster.students.push adds Ken on that const object, the names are copied into students, and seatsLeft -= 1 reassigns the let, which is allowed.
- var leaked is declared for the whole function and assigned again inside the if, so both lines share one function-scoped binding that is still visible after the block.
- The try reads badge after the if, that read throws ReferenceError because the const belongs only to the block, and the catch stores the error name.
- readBeforeInit calls probe before const topic runs, so the temporal dead zone throws ReferenceError instead of handing back undefined.
- letCaptures saves a function on each pass, and each function closes over its own let index, so the three calls return 0, 1, and 2.
- varCaptures saves functions against one function-scoped index, so every call returns 3 after the loop has finished.
- reassignmentVersusMutation pushes a week onto the array held by config, reassigns the let named mode, then catches the TypeError from pointing config at a new object.
- The report is serialized with JSON.stringify, copied into #scope-output with textContent when that node exists, and printed to the console.
Common Pitfalls & Security
Reading a let or const before its line does not yield undefined the way var does. The temporal dead zone throws ReferenceError, including from a function that closed over the binding and ran too early. var hides that mistake and then leaks one binding out of the block, so every timer created in a loop can see the final index. A const object is also easy to mutate by accident when several dashboard widgets share one config object.
- Declaring the same name with let twice in one block is a syntax error, even in cases where var would have been allowed.
- A for loop that uses var together with setTimeout shares one index. Use let when each pass needs its own value.
- const blocks reassignment only. push on a const array still changes the array that other functions can see.
- typeof on a let that is already in scope but not yet initialized still throws. It is not a safe probe inside that block.
- Function declarations hoist differently from var. Put helpers in const bindings or at the top of the module so call order stays obvious.
Best Practices & Modern Standards
Prefer const for every binding that is not reassigned, and switch to let only when a later statement stores a new value. Keep the declaration in the smallest block that needs the name so a loop index or a temporary badge cannot leak into later statements. ES2024 modules and classes are already in strict mode, where an accidental assignment to an undeclared name throws instead of creating a global.
Treat mutation as a separate choice from reassignment. Copy arrays with toSorted, toReversed, or map before a widget edits them, and use Object.freeze on shared course configuration that no page should change. In a classic script, start the file with the strict-mode directive, or load it as a module so strict mode is implied. Read a binding only after its declaration so the temporal dead zone never surprises a quiz timer or a filter.
Real-World Use
A course dashboard keeps the selected track in a let because the student can change it, and it keeps the loaded syllabus in a const because that response should not be replaced by accident. A card builder that closes over the loop index will highlight the wrong lesson if the index was declared with var. With let, each card keeps the index from the pass that created it, so the timer and the filter agree.
The same split shows up in a quiz widget. The question bank stays in a const and is copied before a shuffle, while the current question number is a let. A hint flag declared inside the if that reveals the hint cannot leak into the scoring function, which only sees the names in its own block.
Frequently Asked Questions
Why does const still let me push into an array?
You cannot point the const name at a new array, but the array object itself remains mutable. push, pop, and property assignment change the contents without reassigning the binding. If the contents must stay fixed, copy the array before editing it or freeze it.
What is the temporal dead zone?
The temporal dead zone is the span between entering the block and the line that initializes a let or const. Touching the name in that span throws ReferenceError. The engine knows the binding exists, but it does not fill in undefined the way var does.
Why do three timers with var print the same number?
A var index belongs to the function, not to each loop pass, so every timer function reads that one binding after the loop has finished. The value left behind is the final index. A let index creates a new binding per pass, so each timer prints the number from the pass that created it.
Should new browser code still use var?
New browser code should not use var, because it is function scoped, hoisted as undefined, and braces do not contain it. That model fights ES2024 modules, which are in strict mode and use block scope. Use const until you must reassign, then use let.