Strict Mode ('use strict')
Strict mode catches common JavaScript mistakes and prevents unsafe actions. It makes debugging easier by turning silent errors into real errors. ES modules automatically use strict mode.
Strict Mode
- 'use strict'; — Add at top of file or function to enable strict mode
- Prevents implicit globals — Assigning to undeclared variable throws ReferenceError
- Prevents duplicate params — function(a, a) {} throws SyntaxError
- Prevents this = window — In non-method functions, this is undefined (not window)
- Prevents with statement — with(obj) {} is banned (confusing scope)
- ES modules — Automatically strict. No need for 'use strict' in modules
- Best practice — Always use strict mode or ES modules. Catches bugs early
Strict Mode Code
"use strict";
// ❌ Without strict: creates global variable silently
// mistypedVariable = 42; // ReferenceError in strict mode!
// ❌ Without strict: silently fails
// delete Object.prototype; // TypeError in strict mode!
// ❌ Without strict: duplicates allowed
// function sum(a, a) { } // SyntaxError in strict mode!
// ❌ Without strict: this = window in functions
function checkThis() {
"use strict";
console.log(this); // undefined (not window!)
}
checkThis();
// ❌ Without strict: octal literals allowed
// const n = 010; // SyntaxError in strict mode!
// ✅ In strict mode — all these bugs are caught immediately
// instead of causing weird behavior later
// Strict mode in a function only
function strictFunction() {
"use strict";
// only this function is strict
// let undeclared = 42; // Error only inside this function
}
// ES Modules are automatically strict
// <script type="module" src="app.js">
// No need for "use strict" — it's built in!
console.log("Strict mode catches bugs that would silently fail otherwise");
console.log("Always use strict mode or ES modules!");Tip
Tip
Add 'use strict' at the top of every non-module JavaScript file. It catches common mistakes at parse time: undeclared variables, duplicate parameters, and writing to read-only properties all become errors.
JavaScript looks outward through the scope chain to find variables
Common Mistake
Warning
Thinking strict mode is optional in modern code. ES modules ('import/export') are automatically strict. But if you're writing scripts without module syntax, you must add 'use strict' manually. Without it, typos create global variables silently.
Practice Task
Note
Strict mode: (1) Run code with and without strict mode that assigns to an undeclared variable. (2) Test duplicate parameter names. (3) Try deleting a non-configurable property. Compare the behavior.
Quick Quiz
Key Takeaways
- Strict mode catches common JavaScript mistakes and prevents unsafe actions.
- 'use strict'; — Add at top of file or function to enable strict mode
- Prevents implicit globals — Assigning to undeclared variable throws ReferenceError
- Prevents duplicate params — function(a, a) {} throws SyntaxError