Sub topic 3
Plain Function Calls: Sloppy vs Strict Mode
This chapter assumes you can write functions and function expressions, know how objects and methods work, and have a basic grasp of scope. You have already seen that this depends on how a function is called. This chapter covers the simplest call form, the plain function call, and the rule that applies to it. That rule is called default binding.
Default binding is where most this surprises start, because its result depends on whether the called function runs in sloppy mode or strict mode. Sloppy mode is JavaScript's legacy, non-strict behavior. In sloppy mode a plain call gives you the global object. In strict mode it gives you undefined. If you misjudge which mode applies, you get either a silent data bug or a TypeError.
What Counts as a Plain Call
A plain call is a call where the function is not reached through a property access, is not invoked with new, and is not invoked with call, apply, or bind. These are all plain calls:
function show() {
return this;
}
show(); // identifier call
(function () {})(); // immediately invoked function expression
const f = show; f(); // variable holding a functionThese are not plain calls, and later chapters cover them:
| Call form | Rule that applies |
|---|---|
| `obj.show()` | Implicit binding (method call) |
| `show.call(obj)` | Explicit binding |
| `show.bind(obj)()` | Hard binding |
| `new show()` | `new` binding |
| `show()` | Default binding (this chapter) |
At the language level, a plain call passes undefined as the this value. The function being called then decides what to do with that undefined. Everything in this chapter follows from that one step.
The Two Outcomes
function sloppy() {
return this;
}
function strict() {
'use strict';
return this;
}
// Run as a classic script or a CommonJS file in Node:
console.log(sloppy() === globalThis); // true
console.log(strict()); // undefinedBoth functions receive undefined as their this. The sloppy function replaces undefined with the global object, while the strict function keeps the value it was given. The specification calls this replacement step this coercion, and it applies only to sloppy functions.
Whose Strictness Counts
The mode that matters belongs to the function being called. The mode of the code that calls it does not matter. This is the most common misunderstanding about default binding.
// sloppy-lib.js, a classic script or CommonJS file with no directive
function whoAmI() {
return this;
}
// Strict caller:
(function caller() {
'use strict';
console.log(whoAmI() === globalThis); // true, whoAmI is sloppy
})();The caller is strict, but whoAmI was defined in sloppy code, so its this is coerced to globalThis. The reverse also holds. A strict function called from sloppy code still gets undefined.
The Function constructor gives you a self-contained demonstration. Functions created with new Function never inherit strictness from the surrounding code:
'use strict';
const viaConstructor = new Function('return this');
const viaExpression = function () { return this; };
console.log(viaConstructor() === globalThis); // true, sloppy despite the directive above
console.log(viaExpression()); // undefined, inherits strictnessWhere Strict Mode Comes From
Code becomes strict in several ways. Some of them are implicit, which is why modern code is often strict even when nobody wrote 'use strict'.
| Source | Strict? |
|---|---|
| File or function starting with a `'use strict'` directive | Yes |
| ES module (`<script type="module">`, `.mjs`, `"type": "module"` in package.json) | Yes, always |
| Any code inside a `class` body | Yes, always |
| Functions nested inside strict code | Yes, inherited |
| Classic `<script>` with no directive | No |
| Node CommonJS file (`.js` without `"type": "module"`, or `.cjs`) | No |
| `new Function(...)` body without its own directive | No |
Transpilers and bundlers often add 'use strict' to their output. As a result, code that is sloppy in your source can run as strict in production. When behavior differs between environments, check the emitted code.
Directive Rules
The 'use strict' directive only works when it appears in the directive prologue, the sequence of string literal statements at the very start of a script or function body.
function notStrict() {
const x = 1;
'use strict'; // just an ignored string expression, not a directive
return this;
}
console.log(notStrict() === globalThis); // true in sloppy codeA second rule produces a SyntaxError. A function with non-simple parameters cannot contain its own 'use strict' directive. Non-simple parameters include defaults, destructuring, and rest parameters.
// SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list
// function f(a = 1) {
// 'use strict';
// }
// Fix: make the enclosing scope strict instead.
'use strict';
function f(a = 1) {
return this;
}
console.log(f()); // undefinedWhy Sloppy Default Binding Is Dangerous
In sloppy mode, a plain call that was meant to be a method call or a constructor call writes to the global object without any error.
function User(name) {
this.name = name;
}
const u = User('Ada'); // forgot new
console.log(u); // undefined, User returns nothing
console.log(globalThis.name); // 'Ada', a global variable was createdThe bug shows up far from its cause. Some unrelated code later reads a global name and finds 'Ada'. In a browser it is worse, because window.name is a real property that survives page navigation and converts values to strings.
The same mistake in strict code fails immediately, at the line that caused it:
'use strict';
function User(name) {
this.name = name; // TypeError: Cannot set properties of undefined (setting 'name')
}
try {
User('Ada');
} catch (err) {
console.log(err instanceof TypeError); // true
}The two modes fail in different ways:
| Situation | Sloppy mode | Strict mode |
|---|---|---|
| Read `this.x` in a plain call | Reads `globalThis.x`, usually `undefined` | `TypeError` on reading from `undefined` |
| Write `this.x = 1` in a plain call | Creates or overwrites a global | `TypeError` on writing to `undefined` |
| Where you find out | Later, somewhere else | At the faulty line |
Primitives and null Under Each Mode
This coercion step also applies when this is set explicitly. The call method gets its own chapter later. For now, all you need to know is that fn.call(value) runs fn with this set to value. Sloppy functions coerce whatever they receive, and strict functions keep it unchanged.
function sloppyThis() {
return this;
}
function strictThis() {
'use strict';
return this;
}
console.log(sloppyThis.call(null) === globalThis); // true, null becomes globalThis
console.log(strictThis.call(null)); // null
console.log(typeof sloppyThis.call(42)); // 'object', boxed into a Number wrapper
console.log(typeof strictThis.call(42)); // 'number'
console.log(sloppyThis.call('hi') === 'hi'); // false, it is a String object
console.log(strictThis.call('hi') === 'hi'); // trueThe full sloppy coercion rule:
- If
thisisundefinedornull, replace it withglobalThis. - If
thisis a primitive (number, string, boolean, symbol, bigint), wrap it in its wrapper object. - Otherwise use the object as is.
Strict mode skips all three steps. Boxing has costs. Each sloppy call on a primitive allocates a wrapper object, and the wrapper compares unequal to the original primitive with ===. Library code that extends prototypes with sloppy functions often trips over this.
Edge Cases Worth Knowing
Nested Functions Inside Methods
A function declared inside a method is still a plain call when you invoke it by name. It does not inherit the method's this.
'use strict';
const report = {
title: 'Q3',
print() {
function header() {
return this; // plain call below, so default binding applies
}
return header();
}
};
console.log(report.print()); // undefined, not reportIn sloppy code, header() would return globalThis. Neither result is report. Later chapters show the fixes: arrow functions, bind, or capturing this in a variable.
Detecting the Current Mode
A plain call reveals the mode of the code it is written in:
const isStrict = (function () {
return this === undefined;
})();
console.log(isStrict); // false in a classic script, true in a moduleThis works because the inner function inherits the strictness of its surrounding code, and then default binding exposes it.
Getting the Global Object Reliably
Older code used sloppy default binding on purpose to find the global object: (function () { return this; })(). That trick breaks in strict code and modules. Use globalThis, which works in every mode and every environment.
Practical Guidance
- Write new code as ES modules or classes, which makes it strict without any directive.
- In CommonJS or classic scripts, put
'use strict'at the top of each file. - Treat any
thisinside a function that is called as a plain call as a bug, unless the function never readsthis. - If a library function behaves differently than you expect, check whether that library is sloppy. Its mode controls the result, not yours.
- Lint rules such as ESLint's
no-invalid-thisflagthisin functions that are likely to be called plainly.
Exercise
In a classic (non-module) script with no directives, what does this code log, and why? function outer() { 'use strict'; return inner(); } function inner() { return this === globalThis; } console.log(outer());
Show answer
It logs true. The call inner() is a plain call, so the engine passes undefined as this. inner is defined in sloppy top-level code, and the strict directive in outer does not affect it, because strictness belongs to the called function. So inner coerces undefined to globalThis.
Exercise
A Node CommonJS file defines function Point(x) { this.x = x; } and later runs const p = Point(5); without new. Describe what happens. Then describe what changes if the file is renamed to .mjs.
Show answer
As CommonJS the file is sloppy. Point(5) is a plain call, so this becomes globalThis, globalThis.x is set to 5, and p is undefined. No error is thrown. As .mjs the file is an ES module and therefore strict. this is undefined, so the assignment this.x = x throws a TypeError at that line.
Exercise
Why does function f(a = 0) { 'use strict'; return this; } fail, and how do you make f strict without changing its parameters?
Show answer
A function with non-simple parameters, such as a default value, cannot contain its own 'use strict' directive, so the engine throws a SyntaxError. To make f strict, make the enclosing code strict instead. You can put 'use strict' at the top of the file, wrap f in a strict function, or move it into an ES module or class body.
Exercise
What do sloppyFn.call(true) and strictFn.call(true) return, if both functions are function () { return this; } and only strictFn has a 'use strict' directive?
Show answer
sloppyFn.call(true) returns a Boolean wrapper object, because sloppy functions box primitive this values. typeof on that result is 'object'. strictFn.call(true) returns the primitive true unchanged.