JavaScript's default, "sloppy" mode is forgiving in ways that cause real bugs — it lets you assign to a variable you never declared, silently ignores certain failed assignments instead of throwing, and allows a few syntax patterns that are almost always mistakes. Strict mode is an opt-in setting that tightens all of this up, turning silent problems into loud errors you can actually fix.
Enabling Strict Mode
Add the literal string "use strict" as the very first line of a file or a function. It must come first — nothing else above it, not even a comment that matters to parsing:
"use strict";
x = 10; // throws, because x was never declared with let/const/var
Output:
Uncaught ReferenceError: x is not defined
Without strict mode, that same line would silently create a global variable x — a classic source of hard-to-trace bugs where a typo in a variable name creates a brand-new global instead of raising an error.
What Strict Mode Actually Catches
"use strict";
const user = Object.freeze({ name: "Alex" });
user.name = "Sam"; // throws in strict mode
function sum(a, a, b) { // duplicate parameter name — syntax error in strict mode
return a + b;
}
A few of the most useful changes strict mode makes:
- Assigning to an undeclared variable throws a
ReferenceErrorinstead of creating a global. - Assigning to a read-only or frozen property throws a
TypeErrorinstead of silently doing nothing. - Duplicate function parameter names and duplicate object literal keys become syntax errors.
- Inside a plain function call (not a method),
thisisundefinedinstead of silently defaulting to the global object — catching bugs where you expected a specific object.
You're Probably Already Using It
You rarely need to type "use strict" yourself anymore, because it's automatically on in contexts most modern code already uses:
// Inside any class — strict mode automatically, no directive needed
class Example {
method() {
undeclaredVar = 5; // throws, even with no "use strict" written anywhere
}
}
// Inside an ES module — also strict mode automatically
export function run() {
undeclaredVar = 5; // throws here too
}
Classes and ES6 modules are strict mode by default, with no opt-in required. If you're writing a plain, non-module script with top-level functions (the kind loaded with an ordinary <script> tag), it's worth adding "use strict" explicitly at the top, since that's the one common case where sloppy mode is still the default.
Function-Level Strict Mode
You can also scope it to a single function instead of a whole file, though this is rare in practice now that modules make it automatic:
function strictFn() {
"use strict";
// only this function runs in strict mode
}
