Sub topic 11
Accidental Globals and Strict Mode
This chapter assumes you know how var, let, and const are scoped, and how top-level var in a classic script becomes a property of globalThis (covered in the previous chapter). You should also be comfortable with functions, try...catch, and running code in Node.js or a browser console.
Up to now, every variable in this tutorial was created by a declaration keyword. JavaScript has one more path that skips the keywords completely. If you assign to a name that was never declared, sloppy-mode JavaScript creates a global for you without any warning. This chapter explains how that happens, why it causes bugs, and how strict mode turns it into an error you can see.
How an Accidental Global Is Created
When JavaScript runs an assignment like total = 42, it has to find the binding called total. It starts in the current scope and walks outward through each enclosing scope until it reaches the global scope. If it finds a binding, it updates that binding. If it finds none, the outcome depends on the mode:
- In sloppy mode (the default for classic scripts and CommonJS files), the engine creates a new property named
totalon the global object. - In strict mode, the engine throws a
ReferenceError.
Here is the basic case:
function sloppy() {
total = 42; // no var, let, or const anywhere
}
sloppy();
console.log(globalThis.total); // 42
console.log(total); // 42: visible everywhere nowThe variable total was meant to be local to sloppy. It became a global that any other code can read or overwrite.
Reading Is Different From Writing
The silent creation happens only on assignment. Reading a name that was never declared throws a ReferenceError in both modes:
try {
console.log(notDeclared);
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
console.log(typeof notDeclared); // 'undefined': typeof does not throwtypeof is the one operator that tolerates an undeclared name. That is why older code checks for globals with typeof someLibrary !== 'undefined'.
Common Ways It Happens by Accident
Few people create globals this way on purpose. They come from small mistakes that are easy to miss in review.
Typos
function sumPrices(prices) {
let total = 0;
for (const p of prices) {
totl = total + p; // typo: creates a global named totl
}
return total;
}
console.log(sumPrices([1, 2, 3])); // 0, not 6
console.log(globalThis.totl); // 3The function returns a wrong answer and throws no error. Somewhere else, a global called totl now exists.
Chained Assignment
function reset() {
let a = b = 0; // parsed as: let a = (b = 0);
return a;
}
reset();
console.log(typeof a); // 'undefined': a was local
console.log(b); // 0: b leaked to the global scopeOnly a is declared. The expression b = 0 runs first, and b was never declared, so it becomes a global. To declare both, write let a = 0, b = 0; or use two statements.
Missing Declarations in Loops
function countDown() {
for (i = 3; i > 0; i--) { // forgot let
// ...
}
}
countDown();
console.log(globalThis.i); // 0This one is dangerous because i is a common name. If two functions both leak i and one calls the other inside a loop, each function changes the other's counter.
`this` in a Plain Function Call
There is a related leak that does not use a bare name at all. In sloppy mode, this inside a function called without an object (as fn() rather than obj.fn()) is the global object. If you forget new on a constructor, its property assignments land on globalThis:
function Point(x) {
this.x = x;
}
const p = Point(5); // forgot new
console.log(p); // undefined
console.log(globalThis.x); // 5In strict mode, this is undefined in that call, so this.x = x throws a TypeError instead of polluting the global scope. Class constructors always run in strict mode and throw if you call them without new.
Implicit Globals Versus Declared Globals
An implicit global is a property of the global object, but it is not the same kind of property that a top-level var creates in a classic script. A var property is non-configurable, which means you cannot delete it. An implicit global is configurable, so you can delete it:
implicitValue = 2;
console.log(Object.getOwnPropertyDescriptor(globalThis, 'implicitValue'));
// { value: 2, writable: true, enumerable: true, configurable: true }
console.log(delete globalThis.implicitValue); // true
console.log(typeof implicitValue); // 'undefined'| Created by | Property on globalThis? | Deletable? | Block-scoped? |
|---|---|---|---|
| Top-level `var` (classic script) | Yes | No | No |
| Top-level `let` / `const` | No | Not applicable | Yes |
| Assignment to undeclared name (sloppy) | Yes | Yes | No |
| Assignment to undeclared name (strict) | No, throws ReferenceError | Not applicable | Not applicable |
Strict Mode
Strict mode is an opt-in version of JavaScript, introduced in ES5, that removes some sloppy behaviors and turns several silent failures into thrown errors. The change that matters most for this chapter is that assigning to an undeclared name throws.
'use strict';
function strict() {
missing = 1;
}
try {
strict();
} catch (e) {
console.log(e.name); // 'ReferenceError'
console.log(e.message); // 'missing is not defined'
}The typo in sumPrices would now fail on its first iteration with a clear message, instead of returning a wrong total.
Turning Strict Mode On
You enable strict mode in one of these ways:
- Put
'use strict';as the very first statement of a script. The whole script becomes strict. - Put
'use strict';as the first statement of a function body. Only that function, and any functions nested in it, become strict. - Write an ES module. Modules are always strict, with no directive needed. This covers
<script type="module">in browsers, plus.mjsfiles and.jsfiles in a package with"type": "module"in Node.js. - Write code inside a
classbody. Class bodies are always strict.
Most modern projects use ES modules or a bundler that outputs strict code, so you may already be in strict mode without having written the directive.
The Directive Must Come First
'use strict' is a directive, not a function call. The engine treats it as one only when it appears in the directive prologue, which means it comes before any other statement in the script or function. Anywhere else it is just a string expression that does nothing:
function notStrict() {
const x = 1;
'use strict'; // too late: this is an ordinary expression statement
oops = x; // still sloppy, so this creates a global
}
notStrict();
console.log(globalThis.oops); // 1Comments are allowed before the directive. Any real statement, even a variable declaration, cancels it.
Related Strict-Mode Errors
Strict mode also stops silent failures on writes to global properties that cannot be changed:
'use strict';
try {
undefined = 1; // undefined is a read-only property of globalThis
} catch (e) {
console.log(e.name); // 'TypeError'
}
try {
NaN = 0;
} catch (e) {
console.log(e.name); // 'TypeError'
}In sloppy mode both assignments are silently ignored. The same rule causes the TypeError you saw in an earlier chapter when assigning to a property of an Object.freezed object.
| Situation | Sloppy mode | Strict mode |
|---|---|---|
| Assign to undeclared name | Creates global property | ReferenceError |
| Read undeclared name | ReferenceError | ReferenceError |
| `typeof` undeclared name | `'undefined'` | `'undefined'` |
| `this` in plain function call | `globalThis` | `undefined` |
| Assign to read-only property | Silently ignored | TypeError |
| Delete a non-configurable property | Returns `false` | TypeError |
Defending Against Accidental Globals
Strict mode catches leaks at runtime, but only on the code path that runs. A typo inside a rarely used branch can still wait until production. Use several layers:
- Declare everything. Every variable gets
const,let, or (in legacy code)var. Never rely on assignment to create a variable. - Use ES modules or
'use strict'. This makes leaks throw instead of succeed. - Run a linter. ESLint's
no-undefrule reports undeclared names before the code runs, on every branch. It is enabled in the recommended configuration. - Avoid chained assignment in declarations. Write
let a = 0, b = 0;instead oflet a = b = 0;. - Create intentional globals explicitly. If you really need a global, write
globalThis.appConfig = {...}so readers can see it was deliberate.
Exercises
Exercise
In sloppy mode, what does this code log, and why? function f() { let x = y = 5; } f(); console.log(typeof x, typeof y);
Show answer
It logs undefined number. The statement parses as let x = (y = 5). Only x is declared, and it is local to f, so typeof x outside f is 'undefined'. y was never declared, so the sloppy-mode assignment creates a global property y with the value 5.
Exercise
A developer adds 'use strict'; on the second line of a function, after const start = Date.now();, and then assigns to an undeclared variable elapsed. Does a ReferenceError occur? Explain.
Show answer
No. The directive only takes effect in the directive prologue, which means before any other statement. Because const start = ... comes first, 'use strict' is an ordinary string expression and the function stays in sloppy mode. The assignment to elapsed silently creates a global. Move the directive to the first line of the function, or use an ES module.
Exercise
In a sloppy-mode classic script, var a = 1; and b = 2; both run at the top level. What do delete globalThis.a and delete globalThis.b return, and what explains the difference?
Show answer
delete globalThis.a returns false and delete globalThis.b returns true. A top-level var creates a non-configurable property on the global object, so it cannot be deleted. An implicit global from assigning to an undeclared name is a configurable property, so deletion succeeds. In strict mode, the first delete would throw a TypeError, and the line b = 2 would already have thrown a ReferenceError.
Exercise
Rewrite function Counter() { this.count = 0; } so that calling it without new throws an error instead of creating a global count.
Show answer
Make the function strict, for example function Counter() { 'use strict'; this.count = 0; }, or write it as class Counter { constructor() { this.count = 0; } }. In strict mode, this is undefined in a plain call, so this.count = 0 throws a TypeError. A class constructor throws a TypeError whenever it is called without new.