Strict Mode is a feature in JavaScript that helps you write cleaner, safer, and more secure code by enforcing stricter parsing and error handling rules.
What is Strict Mode?
Strict mode eliminates some silent errors and makes them visible (throws errors). It also prevents the use of unsafe or outdated JavaScript features.
Key Benefits:
- Catches common coding mistakes
- Prevents use of undeclared variables
- Disallows duplicate parameter names
- Makes debugging easier
- Improves performance in some cases
How to Enable Strict Mode
You enable strict mode using a simple directive:
1. For Entire Script
"use strict";
x = 10; // Error: x is not defined
2. Inside a Function
function myFunction() {
"use strict";
y = 20; // Error
}
Example Without Strict Mode
x = 10; // No error (bad practice)
console.log(x);
Example With Strict Mode
"use strict";
x = 10; // ReferenceError
Important Rules in Strict Mode
- No undeclared variables
"use strict";
a = 5; // Error
- No duplicate parameters
function sum(a, a) { } // Error
- No deleting variables
delete x; // Error
thisbehaves differently- In strict mode,
thisisundefinedin functions (not global object)
- In strict mode,
When Should You Use It?
- Always use strict mode in modern JavaScript development
- Especially important for large-scale applications and production code
Pro Tip
If you're using modern JavaScript (ES6 modules), strict mode is automatically enabled.