Js Strict Mode in JavaScript
? JavaScript Strict Mode
Strict Mode is a way to opt into a restricted variant of JavaScript, helping you write safer and cleaner code by catching common mistakes and unsafe actions.
How to Enable Strict Mode
Add this line at the top of your JavaScript file or function:
"use strict";What Does Strict Mode Do?
| Feature | Behavior in Strict Mode |
|---|---|
| Prevents accidental globals | Throws error if you assign to undeclared variables |
| Disallows duplicate parameter names | Syntax error for functions with duplicate params |
Disallows this coercion | this is undefined in functions instead of the global object |
| Prohibits deleting undeletable properties | Throws error if delete is used improperly |
| Disallows use of reserved keywords | Using future reserved words causes errors |
| Throws errors for writing read-only properties | Helps prevent silent failures |
| Disallows octal literals | Octal syntax is invalid |
Example: Accidental Global Variable
"use strict";function foo() { x = 10; // ReferenceError: x is not defined}foo();Without strict mode, x would be created as a global variable silently.
Why Use Strict Mode?
Helps catch bugs early.
Makes your code more optimized by engines.
Improves security by preventing unsafe actions.
Prepares for future ECMAScript versions.
How to Use Strict Mode Locally
You can enable strict mode inside a function only:
function test() { "use strict"; // code here runs in strict mode}If you want, I can explain specific strict mode errors or show how it changes variable behavior!