JavaScript — Strict Mode
Opting in
One string at the top of a file (or function) flips the engine into a cleaner, stricter dialect:
"use strict";
// this whole file now runs strict
What it catches
1. No accidental globals
"use strict";
oops = 5; // ReferenceError — must declare first
Sloppy mode silently created a global; typos became invisible bugs.
2. No silent failures
"use strict";
const frozen = Object.freeze({ x: 1 });
frozen.x = 2; // TypeError instead of quiet no-op
delete Object.prototype; // TypeError
3. Reserved future words locked
let private = 1; // SyntaxError in strict mode
implements, interface, package, private, protected, public, static, let, yield…
4. this sanity (preview)
Inside a plain function call, sloppy-mode this was the global object (window) — a classic bug source. Strict mode sets it to undefined, so mistakes throw immediately instead of corrupting globals.
Scope of activation
"use strict"; // whole file
function local() {
"use strict"; // just this function
}
You're probably already strict
ES modules and classes are automatically strict:
// app.mjs
export const x = 1; // module → strict enforced, no pragma needed
Same inside every class body. Modern tooling (bundlers with ESM output) means most real projects run strict everywhere without writing the directive.
Should you write it?
- Plain
<script>files on classic pages → yes, add it top-of-file - Modules/bundled code → already active; harmless if present
- Legacy codebases → test before flipping; it exposes latent bugs (that's the point)
Debugging bonus story
function Counter() { count = 0; } // typo'd param!
Counter();
console.log(window.count); // sloppy: 0 leaked globally 😱
Strict turns that into an immediate ReferenceError pointing at the guilty line.
Mini Practice
- Create an implicit global without the pragma; watch it land on window
- Add
"use strict"; rerun and catch the new ReferenceError - Freeze an object; mutate under both modes; compare silence vs TypeError
- Confirm your bundled/module code is already strict (try the oops assignment)
Next: modules →
Related Topics
Frequently Asked Questions about Strict Mode
What is Strict Mode in JavaScript?
Strict Mode is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Strict Mode?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strict Mode.
Why is Strict Mode important in JavaScript?
Strict Mode is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.