'use strict'; Restrictions & SafetyStrict Mode (introduced in ES5) opts JavaScript into a restricted variant of the language that intentionally eliminates silent errors, enforces variable declaration, prevents reserved keyword usage, and improves runtime performance optimization.
flowchart TD
StrictMode["'use strict'; Enabled"] --> NoUndeclared["Throws ReferenceError on undeclared assignments (x = 10)"]
StrictMode --> NoSilentFail["Throws TypeError on assignment to read-only properties"]
StrictMode --> CleanThis["Global 'this' in plain functions is undefined (not Window)"]
StrictMode --> SafeEval["eval() cannot introduce variables into surrounding scope"]
| Behavior / Action | Non-Strict Mode (Sloppy) | Strict Mode ('use strict';) |
|---|---|---|
Assign to undeclared variable (x = 5) |
Creates implicit global variable | Throws ReferenceError |
this in plain function calls |
Binds to global object (window) |
undefined |
Duplicate parameter names (fn(a, a)) |
Allowed (Second shadows first) | Throws SyntaxError |
| Mutating read-only property | Fails silently | Throws TypeError |
| ES6 Modules / Classes | Non-strict by default | Strict Mode enabled automatically |
// Demonstrating strict mode enforcement
"use strict"; // Opt-in to strict mode for script or function scope
// 1. Undeclared Variable Assignment Protection
function testUndeclared() {
try {
// implicitGlobal = 42; // Throws ReferenceError in strict mode!
} catch (e) {
console.error(`Strict Error: ${e.message}`);
}
}
testUndeclared();
// 2. Strict Mode 'this' Behavior
function checkThisBinding() {
console.log(`Strict mode function 'this': ${this}`); // undefined!
}
checkThisBinding();
// 3. Read-Only Property Protection
const frozenObj = Object.freeze({ role: "admin" });
try {
// frozenObj.role = "editor"; // Throws TypeError in strict mode!
} catch (e) {
console.error(`Read-Only Error: ${e.message}`);
}
import/export) and ES6 class bodies execute in Strict Mode automatically without needing 'use strict';.'use strict'; as the very first statement before any code.Explain why function test() { console.log(this); } test(); logs undefined in Strict Mode instead of window.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.