Sub topic 13
Accidental Globals and Strict Mode
This chapter assumes you know how the scope chain resolves a name, what the global scope is, and how var hoisting works. You should be able to run a script file in Node.js or paste code into a browser console. The examples assume a classic script or a Node.js CommonJS file (.js without "type": "module"). Both run in sloppy mode by default.
Earlier chapters showed what the engine does when it reads a name: it walks the scope chain outward and throws a ReferenceError if no scope declares the name. Writing to a name is different. In sloppy mode, assigning to a name that no scope declares does not fail. The engine quietly creates a property on the global object instead. This chapter explains how that happens, why it causes bugs, and how strict mode stops it.
How an Assignment Resolves a Name
An assignment such as total = 10 resolves total with the same scope-chain walk used for reads. The two cases differ only when the walk reaches the global scope without finding a declaration:
- Reading an undeclared name throws a
ReferenceErrorin every mode. - Writing an undeclared name in sloppy mode creates a new property on the global object (
globalThis, which iswindowin browsers). - Writing an undeclared name in strict mode throws a
ReferenceError.
The topic spine's core example shows both branches:
function leakSloppy() {
leaked = 1; // no declaration
}
leakSloppy();
console.log(globalThis.leaked); // 1
function leakStrict() {
"use strict";
try {
alsoLeaked = 1;
} catch (e) {
console.log(e.name); // "ReferenceError"
}
}
leakStrict();leakSloppy never declares leaked, so the assignment falls through to the global object. After the function returns, leaked stays visible to every script on the page or in the process. leakStrict runs the same kind of assignment under strict mode, and the engine refuses it.
Why Implicit Globals Cause Bugs
An implicit global is a global variable that the code never declared. It causes trouble in three ways.
First, it hides typos. If you declare let userCount and later write userCuont = 5, sloppy mode creates a new global called userCuont. Your real variable never changes, and nothing reports an error.
Second, it creates shared state that nobody planned for. Two unrelated functions that both forget to declare i or result end up writing to the same global, and each one corrupts the other's value.
Third, it outlives the function. A local variable disappears when nothing refers to it any more. An implicit global stays alive as long as the global object does.
Common Ways Globals Leak
Some leaks are easy to miss because the code looks like it declares everything.
Chained assignment. A declaration keyword applies only to the first name in a chained assignment:
function init() {
let a = b = 0; // parsed as: let a = (b = 0);
return a;
}
init();
console.log(typeof b); // "number" (b leaked to the global object)let declares a. The inner expression b = 0 is a plain assignment to an undeclared name, so b becomes a global. Write let a = 0, b = 0; or use two separate statements.
Loop counters without a keyword. Writing for (i = 0; i < n; i++) without let creates a global i. A nested function that does the same thing will share the same i, and the loops will interfere with each other.
Forgetting new. In sloppy mode, a plain function call sets this to the global object. A constructor called without new writes its fields onto 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 a plain call. The statement this.x = x then throws a TypeError because it tries to set a property on undefined. The leak becomes an error you can see.
Implicit Globals Versus Declared Globals
An implicit global differs from a variable declared with var at the top level of a classic script. Both become properties of the global object, but their property attributes are different:
function makeLeak() {
leakedCounter = 10;
}
makeLeak();
console.log(Object.getOwnPropertyDescriptor(globalThis, "leakedCounter"));
// { value: 10, writable: true, enumerable: true, configurable: true }
console.log(delete globalThis.leakedCounter); // true
console.log(typeof leakedCounter); // "undefined"An implicit global is configurable: true, so delete removes it. A top-level var in a classic browser script creates a property with configurable: false, so delete on it returns false and the variable stays. Top-level let, const, and class do not create properties on the global object at all. They live in a separate declarative record that belongs to the global scope.
| Kind of global | Property on `globalThis`? | Deletable? | Has a TDZ? |
|---|---|---|---|
| Implicit (sloppy assignment) | Yes | Yes | No |
| Top-level `var` in a classic script | Yes | No | No |
| Top-level `function` declaration | Yes | No | No |
| Top-level `let` / `const` / `class` | No | No | Yes |
What Strict Mode Is
Strict mode is an opt-in variant of JavaScript, added in ES5, that turns several silent failures into thrown errors and removes some confusing features. The behaviors that matter for scope are:
| Situation | Sloppy mode | Strict mode |
|---|---|---|
| Assigning to an undeclared name | Creates a global property | `ReferenceError` |
| `this` in a plain function call | `globalThis` | `undefined` |
| Assigning to a read-only global such as `undefined` or `NaN` | Silently ignored | `TypeError` |
| `delete` on a plain variable name | Returns `false` | `SyntaxError` |
| `with` statement | Allowed | `SyntaxError` |
| `eval` declaring a `var` | Leaks into the surrounding scope | Stays inside the `eval` |
The last two rows matter for scope as well. In sloppy mode, with and eval can add bindings at run time, so the engine cannot tell from the source code where a name will resolve. Strict mode removes both, which makes scope purely lexical.
Enabling Strict Mode
You turn strict mode on in one of these ways:
- Put the directive
"use strict";as the first statement of a script. The whole script becomes strict. - Put the directive as the first statement of a function body. Only that function, and any functions nested inside it, become strict.
- Write ES modules. Module code is always strict, with no directive needed.
- Write class bodies. Code inside a
classis always strict, even in a sloppy script.
"use strict";
function update() {
try {
countr = 1; // typo for "counter"
} catch (e) {
console.log(e.message); // "countr is not defined"
}
}
update();Gotchas with the Directive
- The directive only works as the first statement. If any other statement comes before
"use strict";, the engine treats it as an ordinary string expression and ignores it, without any warning. Comments before the directive are fine. - Strict mode cannot be turned off for an inner function once an outer scope enables it.
- A function whose parameters use defaults, destructuring, or rest syntax cannot contain its own
"use strict";. For example,function f(a = 1) { "use strict"; }is aSyntaxError. Put the directive at the script level, or use a module. - When build tools concatenate files, a directive at the top of one file can make the whole bundle strict, or it can end up in the middle of the bundle and stop working. Function-level directives or modules avoid this problem.
Choosing a Strategy
| Codebase | Recommended approach |
|---|---|
| New code, any environment | ES modules (strict mode by default) plus a linter |
| Legacy classic scripts | `"use strict";` inside an IIFE or in each top-level function |
| Mixed third-party scripts on one page | Function-level directives, so other scripts keep their original mode |
| Code you cannot change | A linter and `Object.keys(globalThis)` checks in tests to find leaks |
Strict mode does not make undeclared assignments safe. It makes them loud. You still have to declare every variable with let, const, or var. Strict mode makes sure that a missing declaration shows up as an error.
Exercise
In sloppy mode, what does this code print, and what prints if you add "use strict"; as the first line of the file? function setup() { const config = mode = "dev"; return config; } setup(); console.log(typeof mode);
Show answer
In sloppy mode it prints "string". const declares only config, and mode = "dev" is an assignment to an undeclared name, so it creates a global property. With "use strict"; the assignment to mode throws a ReferenceError inside setup(), and the console.log line never runs.
Exercise
A sloppy-mode script creates leakA with a plain assignment inside a function and declares var leakB = 1; at the top level of a classic browser script. What do delete globalThis.leakA and delete globalThis.leakB return, and why?
Show answer
delete globalThis.leakA returns true because implicit globals are created as configurable properties. delete globalThis.leakB returns false because a top-level var creates a non-configurable property on the global object, so it cannot be deleted.
Exercise
Why does calling a constructor without new fail loudly in strict mode but not in sloppy mode?
Show answer
In a plain function call, sloppy mode sets this to the global object, so this.x = ... quietly writes a global property. Strict mode sets this to undefined, so setting a property on it throws a TypeError.