Strict Mode
Strict mode is a restricted version of JavaScript, introduced in ES5 (2009), that turns several silent mistakes into errors, removes a few confusing features, and makes code easier for engines to optimize. You switch it on with the directive "use strict"; at the top of a script or function. ES modules and classes are always strict, so most modern code already runs in strict mode without asking for it. Knowing what changes helps you read errors and understand older code that runs in "sloppy mode".
In One Minute
- Turn it on with
"use strict";as the first statement of a file or function. - Modules (
type="module",.mjs,import/export) and class bodies are strict automatically. - Assigning to an undeclared variable throws
ReferenceErrorinstead of creating a global. - Writes that used to fail silently (to read-only properties, to frozen objects) throw
TypeError. - In a plain function call,
thisisundefinedinstead of the global object.
Turning It On
Syntax
"use strict"; // first statement of a script: the whole script is strict
function f() {
"use strict"; // first statement of a function: only this function is strict
}The directive must come first (only comments and other directives may precede it). Anywhere else it is just an unused string and does nothing. Strictness also applies to every function nested inside.
| Code | Strict? |
|---|---|
<script type="module">, .mjs files, files using import/export | Always |
Code inside a class body | Always |
A classic script or Node.js CommonJS file starting with "use strict"; | Yes |
A function whose first statement is "use strict"; | Yes (that function only) |
| Anything else | No ("sloppy mode") |
What Changes
No Accidental Globals
In sloppy mode, assigning to a name that was never declared quietly creates a global variable, so a typo becomes a brand new variable. Strict mode throws:
"use strict";
let balance = 120;
try {
balanse = 80; // typo
} catch (err) {
console.log(err.name + ": " + err.message);
}
console.log(balance);ReferenceError: balanse is not defined
120Without strict mode, the typo would have created a global balanse = 80, and balance would have stayed 120 with no error at all.
Silent Failures Become Errors
Some operations fail without telling you in sloppy mode. Strict mode makes them throw:
"use strict";
const settings = Object.freeze({ currency: "USD" });
try {
settings.currency = "EUR";
} catch (err) {
console.log(err.name + ": " + err.message);
}
try {
"fee".length = 10;
} catch (err) {
console.log(err.name + ": " + err.message);
}
try {
delete Object.prototype;
} catch (err) {
console.log(err.name + ": " + err.message);
}TypeError: Cannot assign to read only property 'currency' of object '#<Object>'
TypeError: Cannot assign to read only property 'length' of string 'fee'
TypeError: Cannot delete property 'prototype' of function Object() { [native code] }In sloppy mode, all three lines would do nothing and report nothing, leaving you to wonder why the value didn't change.
Safer this in Plain Calls
When a function is called without an object (f() rather than obj.f()), sloppy mode sets this to the global object, so a constructor called without new writes to window. Strict mode sets this to undefined:
function sloppyThis() {
return this === globalThis;
}
function strictThis() {
"use strict";
return this;
}
console.log(sloppyThis());
console.log(strictThis());true
undefinedWith this as undefined, a mistake like calling a constructor without new fails at once (TypeError: Cannot set properties of undefined) instead of polluting the global object.
Other Changes
| Sloppy mode | Strict mode |
|---|---|
Duplicate parameter names function f(a, a) allowed | SyntaxError |
Octal literals like 012 (means 10) | SyntaxError; write 0o12 |
with statement allowed | SyntaxError |
eval can create variables in the surrounding scope | eval gets its own scope |
arguments stays linked to parameters (changing one changes the other) | Not linked |
arguments.callee allowed | TypeError |
Future reserved words (implements, interface, package, private, protected, public, static, yield, let) usable as names | SyntaxError |
Modules and Classes Are Strict by Default
If you write ES modules (which modern browsers, Node.js and every build tool support), you are already in strict mode. There's no need to write "use strict" in a module, and adding it changes nothing.
class Account {
setOwner() {
try {
undeclaredOwner = "Navika";
} catch (err) {
return err.name;
}
}
}
console.log(new Account().setOwner());ReferenceErrorThe function containing this class isn't strict, but the class body is, so the undeclared assignment throws.
In Practice
Older Fee Tracker code written as a classic script can opt in to strict mode one function at a time, which is a safe way to modernize: each strict function throws where it used to fail silently, so problems show up in testing instead of in production data:
function applyDiscount(record, rate) {
"use strict";
if (Object.isFrozen(record)) {
return { ...record, fee: record.fee * (1 - rate) };
}
record.fee = record.fee * (1 - rate);
return record;
}
const frozen = Object.freeze({ name: "Advitha", fee: 450 });
console.log(applyDiscount(frozen, 0.1));
console.log(frozen.fee);{ name: 'Advitha', fee: 405 }
450Wrapping a whole legacy file at once is riskier: concatenating a strict file with a sloppy one (as old build tools did) could make the sloppy code strict too. Function-level directives avoid that.
Common Mistakes
Putting "use strict" after other code. It must be the first statement, or it is ignored.
Adding it to every module. Harmless but pointless: modules are already strict.
Assuming a strict function makes callers strict. It applies only to the function (and functions nested inside it).
Turning on strict mode for old code without testing. Code that depended on sloppy behavior (implicit globals, this as window) will start throwing.
Practice
Challenge: The function below has a typo that silently creates a global in sloppy mode. Add strict mode to the function so the typo throws, and catch the error to print its message.
function addFee(total, fee) {
totl = total + fee;
return total;
}Show solution
function addFee(total, fee) {
"use strict";
totl = total + fee;
return total;
}
try {
addFee(100, 20);
} catch (err) {
console.log(err.message);
}totl is not definedKey Takeaways
| Change | Strict mode |
|---|---|
| Undeclared assignment | ReferenceError |
| Write to read-only property | TypeError |
this in f() | undefined |
with, 012 octals | SyntaxError |
| Modules, classes | Strict automatically |
Was this tutorial helpful?