Strict Mode in JavaScript

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?

  1. 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).
  2. Prohibits certain syntax: Such as the with statement, duplicate function parameters, etc.
  3. Improves performance: Limits side effects of eval and arguments, making it easier for the engine to optimize.

How to Enable Strict Mode

  1. 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
    
  2. 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

  1. Variables Must Be Declared

    "use strict";
    x = 1; // ReferenceError: x is not defined
    

    In non-strict mode, this would implicitly create a global variable.

  2. Prohibits Deleting Non-Deletable Properties

    delete Object.prototype; // TypeError: Cannot delete property 'prototype'
    
  3. Function Parameters Cannot Have Duplicate Names

    function dup(a, a) { "use strict"; } // SyntaxError: Duplicate parameter name
    
  4. Prohibits the with Statement

    "use strict";
    with (obj) { } // SyntaxError: Strict mode code may not include a with statement
    
  5. this Defaults to undefined (Instead of the Global Object in Non-Strict Mode)

    function showThis() {
      "use strict";
      console.log(this); // undefined
    }
    showThis();
    
  6. Prohibits Octal Literals

    "use strict";
    let n = 010; // SyntaxError: Octal literals are not allowed
    
  7. eval No Longer Leaks Variables into the Outer Scope

    "use strict";
    eval("var z = 1;");
    console.log(z); // ReferenceError: z is not defined
    
  8. 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.