JavaScript Strict Mode Explained
Strict mode in JavaScript is a way to enforce stricter parsing and error handling in your code. It helps you write cleaner, safer, and more secure JavaScript by catching common coding mistakes and bugs early.
1. How to Enable Strict Mode
You enable strict mode by adding the directive "use strict"; at the beginning of a script or function.
"use strict";
Must be at the top of the file or function.
2. Strict Mode in Whole Script
Example:
"use strict";
x = 5; // Error: x is not defined
console.log(x);
Output
ReferenceError: x is not defined
Why?
Strict mode does not allow undeclared variables. You must use let, const, or var.
3. Strict Mode in a Function Only
You can also enable strict mode inside a single function.
Example:
function demo() {
"use strict";
y = 10; // Error inside strict mode
}
demo();
Common Restrictions in Strict Mode
Rule | Without Strict Mode | With Strict Mode |
---|---|---|
Undeclared variables | Allowed | Error |
Assigning to read-only property | Fails silently | Error |
Duplicated parameter names | Allowed | Error |
this in functions | Global (window) | undefined |
Deleting variables/functions | Allowed (fails silently) | Error |
Using future reserved keywords | Allowed | Error |
Example: Duplicate Parameters
"use strict";
function test(a, a) { // SyntaxError
console.log(a);
}
Output
SyntaxError: Duplicate parameter name not allowed in this context
Example: this in Strict Mode
"use strict";
function showThis() {
console.log(this);
}
showThis(); // undefined, not window/global
Output
undefined
In non-strict mode, this would refer to the global object (like window in browsers).
Benefits of Using Strict Mode
- Catches silent errors
- Makes code more secure
- Prepares code for future JavaScript versions
- Helps avoid common bad practices