JavaScript · Lesson 2
Scope, Hoisting and Strict Mode
Where a name is visible (block, function, module and global scope), when it exists (hoisting and the temporal dead zone), why var in a loop breaks callbacks, what const really protects, and what strict mode changes.
In short
varis function scoped;letandconstare block scoped- Lookups walk outward through the scope chain, by where code is written
- Hoisting: functions with their body,
varasundefined,let/constin the TDZ - In loops,
letgives each callback its own variable constprotects the binding;Object.freezeis shallow- Strict mode turns silent mistakes into errors
Scope answers "where can I use this name?". Hoisting answers "from when does it exist?". If you come
from C# or TypeScript, let and const will feel familiar: they're block scoped, like C# locals. The surprises
come from var, from function declarations that work before the line they're on, and from the global object.
You'll still meet all three in older code, in interview questions, and in bugs.
Every JavaScript snippet below has a ▶ Try button. Predict the output, then run it. The lab runs your code in strict mode with module-like scoping, the way ES modules and bundlers run it. The last part of this lesson shows what strict mode changes.
Three ways to declare a variable
var | let | const | |
|---|---|---|---|
| Scope | the whole function | the block { ... } | the block |
| Before its line | exists, value undefined | exists, but using it throws (TDZ) | exists, but using it throws (TDZ) |
| Redeclare in the same scope | allowed | SyntaxError | SyntaxError |
| Reassign | yes | yes | no (TypeError) |
| At the top level of a classic script | becomes a property of window | doesn't | doesn't |
Modern code uses const by default and let when the variable really changes. var is legacy. The ESLint
rules no-var and prefer-const enforce this. You still need to understand var, because it's everywhere in
older code and tutorials, and because it explains several classic bugs.
Block scope vs function scope
A block is any pair of braces: an if, a loop body, a try, or a bare { }. let and const live in
the nearest block. var ignores blocks and belongs to the nearest function (or to the module or script, if
there is no function).
function checkout(items) {
if (items.length > 0) {
var total = items.length * 10; // var: scoped to the whole function
let discount = 5; // let: only inside this if block
console.log('inside:', total, discount);
}
console.log('after the if, total is', total);
try {
console.log(discount);
} catch (e) {
console.log(e.name + ': ' + e.message);
}
}
checkout([1, 2, 3]);
A loop counter declared with var is visible after the loop too, and so is any var declared inside the loop
body. With let, each block keeps its variables to itself.
The scope chain
Scopes nest. When code uses a name, JavaScript looks in the current scope first, then in the scope that
encloses it in the source code, and so on outward, up to the global scope. The first match wins. If nothing
matches, reading the name throws a ReferenceError.
const app = 'shop';
function outer() {
const user = 'ann';
function inner() {
const item = 'book';
console.log(item, user, app); // found in inner, outer, then the module scope
}
inner();
}
outer();
The chain is decided by where a function is written, not by where it's called. This is called lexical scope:
const label = 'module';
function show() {
console.log(label); // the label next to where show() is written
}
function caller() {
const label = 'caller';
show(); // still prints "module": callers don't lend their variables
}
caller();
Every scope is an environment record: a little table of names to values, with a link to its parent. A function keeps a link to the environment it was created in. That link is what a closure is. The next topic, Functions and Closures, builds on it. The scope chain resolver exercise implements environment records directly.
Shadowing
An inner scope can declare a name that already exists outside. Inside, the inner one shadows (hides) the outer one.
const status = 'outer';
{
const status = 'inner'; // a new variable that hides the outer one
console.log(status);
}
console.log(status);
Shadowing is legal, and sometimes useful, but it's a common source of "why didn't my variable change?" bugs.
Many teams turn on the no-shadow lint rule. Note that C# forbids reusing a local's name in a nested block, while
JavaScript allows it.
Hoisting: names exist before their line runs
Before a scope runs any code, JavaScript creates all the bindings declared in it. This is called hoisting. What each binding holds before its declaration line depends on how it was declared:
- Function declarations are created with their body. You can call them above the line where they are written.
varis created and set toundefined.let,constandclassare created but uninitialized. Touching them before their declaration line throws aReferenceError. The time between "the scope starts" and "the declaration runs" is the temporal dead zone (TDZ).
console.log(greet('ann')); // works: function declarations are hoisted with their body
console.log(typeof legacy); // "undefined": var is hoisted as undefined
try {
console.log(modern);
} catch (e) {
console.log(e.name + ': ' + e.message);
}
function greet(name) {
return 'hello ' + name;
}
var legacy = 'old';
let modern = 'new';
A function expression (or an arrow function) is just a value assigned to a variable. Only the variable is hoisted, so calling it too early fails, and how it fails depends on the keyword:
try {
save();
} catch (e) {
console.log('var:', e.name + ': ' + e.message);
}
try {
load();
} catch (e) {
console.log('const:', e.name + ': ' + e.message);
}
var save = function () {};
const load = () => {};
The TDZ is about time, not position in the file. A function may mention a let that is declared further
down, as long as it's called after the declaration has run:
function report() {
return `limit is ${limit}`; // fine: by the time report() runs, limit is initialized
}
const limit = 10;
console.log(report());
Why does the TDZ exist at all? It turns "used too early" into a loud error instead of a silent undefined.
const couldn't work any other way: a constant that's undefined first and 10 later wouldn't be constant.
Even typeof, which is normally safe on unknown names, throws in the TDZ. typeof notDeclaredAnywhere gives
'undefined', but typeof x just before let x throws.
The classic bug: var in a loop
const viaVar = [];
for (var i = 0; i < 3; i++) {
viaVar.push(() => i);
}
const viaLet = [];
for (let j = 0; j < 3; j++) {
viaLet.push(() => j);
}
console.log(viaVar.map((f) => f()));
console.log(viaLet.map((f) => f()));
With var, there is one i for the whole function. All three arrow functions close over that same
variable, and by the time they run the loop has finished and i is 3. With let, a for loop creates a
fresh binding for every iteration and copies the current value into it, so each callback gets its own j.
The same bug shows up with timers and event handlers:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var timer', i), 0);
}
for (let k = 0; k < 3; k++) {
setTimeout(() => console.log('let timer', k), 0);
}
Before let existed (ES2015), the fix was an IIFE, an immediately invoked function expression, that
created a new function scope per iteration: (function (n) { setTimeout(() => log(n)); })(i). You'll still see
that pattern in older code. Today, let is the fix.
const protects the binding, not the value
const means the variable can't be pointed at something else. The object it points to can still change:
const config = { retries: 3, db: { host: 'localhost' } };
config.retries = 5; // allowed: the object is mutable
config.db.host = 'prod-db'; // allowed
try {
config = {}; // not allowed: the binding is constant
} catch (e) {
console.log(e.name + ': ' + e.message);
}
const frozen = Object.freeze({ retries: 3, db: { host: 'localhost' } });
try {
frozen.retries = 5;
} catch (e) {
console.log(e.name + ': ' + e.message);
}
frozen.db.host = 'oops'; // freeze is shallow: nested objects stay mutable
console.log(frozen.db.host);
Object.freeze(obj)makes the object's own properties read-only and stops new ones being added. It is shallow, so nested objects need their own freeze (the deep freeze exercise).- In strict mode, writing to a frozen object throws. In sloppy mode, the write is silently ignored, which is worse.
- TypeScript's
readonlyandas constare compile-time only. They don't freeze anything at runtime.
The global scope and globalThis
The outermost scope depends on how the code is loaded:
- In a classic browser
<script>, top-levelvarand function declarations become properties of the global object (window.myVar). Top-levelletandconstare global too, but they aren't properties ofwindow. Every script on the page shares this one global scope, which is why old code wrapped everything in an IIFE. - In an ES module (and in Node's CommonJS files, which Node wraps in a function), top-level declarations are local to that file. Nothing leaks.
globalThisis the standard name for the global object everywhere:windowin pages,selfin workers,globalin Node.
The lab works like a module: top-level declarations stay local.
var answer = 42;
let mode = 'lab';
console.log(globalThis.answer, globalThis.mode); // both undefined: nothing leaked
globalThis.appVersion = '1.4.0'; // creating a real global takes an explicit write
console.log(appVersion); // found at the end of the scope chain
Strict mode
Strict mode is an opt-in "safer JavaScript" from ES5 (2009). It turns several silent failures into errors and removes a few confusing features. You get it by:
- writing
'use strict';as the first statement of a script or a function, or - writing an ES module or a class body, which are always strict.
Since nearly all modern code is modules (TypeScript, Vite, webpack and Angular all emit modules), you are almost
always in strict mode already. The exception is Node's CommonJS files (.cjs, or .js without
"type": "module"): they're sloppy unless they start with 'use strict'. What it changes:
| Situation | Sloppy mode | Strict mode |
|---|---|---|
Assigning to an undeclared name (totl = 5, a typo) | creates a global variable | ReferenceError |
| Writing to a read-only, getter-only or frozen property | silently ignored | TypeError |
| Adding a property to a non-extensible object | silently ignored | TypeError |
this in a plain function call f() | the global object | undefined |
Duplicate parameter names function f(a, a) | allowed | SyntaxError |
with statements, octal literals like 0755 | allowed | SyntaxError |
delete someVariable | returns false | SyntaxError |
Names like let, static, implements, package | usable as identifiers | reserved |
The lab can't run sloppy code directly, but the Function constructor creates functions that are not strict
unless their body says so. That makes a handy demo of the first and fourth rows:
const sloppy = new Function('totl = 5; return typeof this;');
console.log('sloppy:', sloppy(), globalThis.totl); // a typo became a global variable
const strict = new Function("'use strict'; totl2 = 5;");
try {
strict();
} catch (e) {
console.log('strict:', e.name + ': ' + e.message);
}
function whoAmI() {
return this;
}
console.log('this in a strict function call:', whoAmI());
The this rule matters most day to day. Passing a method around as a callback (setTimeout(user.save),
onClick={this.handle}) loses its this. In strict mode this is undefined, so the bug throws right away
instead of quietly reading properties of the global object. The How this Works topic covers it.
Private state with a function scope
Before ES modules and #private class fields, the module pattern used a function's scope to hide state.
The variables live in the function's scope. Only the returned functions can reach them.
function createCounter() {
let count = 0; // private: nothing outside can see it
return {
increment: () => ++count,
reset: () => { count = 0; },
get value() { return count; },
};
}
const clicks = createCounter();
clicks.increment();
clicks.increment();
console.log(clicks.value, clicks.count); // 2 undefined
You'll see the IIFE version in older libraries (const api = (function () { ... return { ... }; })();) and in
Node's module wrapper. Today, each ES module file gives you this privacy for free.
Coming from C# or TypeScript
Side note
letandconstwork like C# locals. They're block scoped, and using one before its declaration is an error. In C# that's a compile error. In JavaScript it's a runtimeReferenceError(TDZ), and TypeScript catches most cases at compile time.varhas no C# equivalent. Function scope plus hoisting plus redeclaration is unique to JavaScript. Treat it as legacy.constis not C#const. C#constis a compile-time constant value. JavaScriptconstis a binding that can't be reassigned, and the object behind it can still change. It's closer to areadonlylocal reference.- JavaScript allows shadowing in nested blocks, which C# forbids (error CS0136).
- Closures capture variables, not values, in both languages. C# 5 changed
foreachto give each iteration a fresh variable for exactly the reason thevarloop bug happens.for (int i...)lambdas in C# still sharei.
In real codebases
Side note
constby default,letwhen you reassign, nevervar: the lint rules areprefer-constandno-var. Addno-shadow,no-use-before-defineandblock-scoped-varif your team likes guard rails.- Everything in an ES module is strict. Code that only "works" in sloppy mode (implicit globals, writes to frozen objects being ignored) breaks when it's moved into a module. That's usually a hidden bug being revealed, not a new one.
- Don't put things on
globalThisorwindow. Export them from a module or inject them. The few exceptions are polyfills and feature detection ('IntersectionObserver' in globalThis). - In React, a stale value in an event handler or effect is the same mechanism as the
varloop bug: a closure sees the variables of the render it was created in. - Freeze config objects and constants you share across modules, or rely on TypeScript's
readonlyplus code review. Remember that bothObject.freezeandreadonlyare shallow.
The exercises
- Fix the loop closures: per-iteration bindings with
let, for callbacks and timers. (easy) - A counter with private state: the module pattern. (easy)
- Deep freeze a config:
const,Object.freezeand strict mode errors. (medium) - A tiny module registry: function scopes as modules, the way pre-ES2015 code organized itself. (medium)
- Scope chain resolver: environment records, shadowing, the TDZ and
const. (medium) - Scope linter: find redeclarations and shadowing statically, with
varhoisting through blocks. (hard) - Hoisting interpreter: run tiny programs exactly the way JavaScript would, including hoisting and the TDZ. (hard)
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app