Strict Mode in JavaScript
Description
Strict Mode is a JavaScript execution mode introduced in ES5 that makes code safer and more aligned with modern standards by throwing more errors and disabling certain unsafe syntax. When Strict Mode is enabled, the engine optimizes code execution and helps avoid common coding mistakes.
Why Use Strict Mode?
- Eliminates implicit errors: For example, assigning a value to an undeclared variable will throw an error (in non-strict mode, it creates a global variable).
- Prohibits certain syntax: Such as the
withstatement, duplicate function parameters, etc. - Improves performance: Limits side effects of
evalandarguments, making it easier for the engine to optimize.
How to Enable Strict Mode
- Enable Globally: Add
"use strict";at the top of a script file or within a<script>tag."use strict"; x = 10; // Error: x is not defined - Enable Within a Function: Add
"use strict";at the top of a function body (only applies to that function).function strictFunc() { "use strict"; y = 20; // Error }
Key Changes in Strict Mode
-
Variables Must Be Declared
"use strict"; x = 1; // ReferenceError: x is not definedIn non-strict mode, this would implicitly create a global variable.
-
Prohibits Deleting Non-Deletable Properties
delete Object.prototype; // TypeError: Cannot delete property 'prototype' -
Function Parameters Cannot Have Duplicate Names
function dup(a, a) { "use strict"; } // SyntaxError: Duplicate parameter name -
Prohibits the
withStatement"use strict"; with (obj) { } // SyntaxError: Strict mode code may not include a with statement -
thisDefaults toundefined(Instead of the Global Object in Non-Strict Mode)function showThis() { "use strict"; console.log(this); // undefined } showThis(); -
Prohibits Octal Literals
"use strict"; let n = 010; // SyntaxError: Octal literals are not allowed -
evalNo Longer Leaks Variables into the Outer Scope"use strict"; eval("var z = 1;"); console.log(z); // ReferenceError: z is not defined -
Prohibits Assigning Values to Read-Only Properties (e.g.,
arguments.caller)"use strict"; arguments.caller = "test"; // TypeError
Considerations for Strict Mode
- If your code relies on non-strict mode features (like automatic global variable creation), enabling Strict Mode may cause errors.
- When merging scripts, if some code enables Strict Mode, be mindful of scope isolation (to avoid affecting non-strict code).
Practical Application Suggestions
- For new projects, it is recommended to enable Strict Mode globally to avoid potential errors.
- When migrating legacy projects, you can start by enabling Strict Mode for individual functions and gradually fix issues.