Strict mode is a way to opt into a restricted variant of JavaScript that eliminates some silent errors and prevents unsafe actions. It was introduced in ES5.

Enabling Strict Mode

Place "use strict"; at the top of a script or module:

  "use strict";

x = 10; // ReferenceError: x is not defined (no accidental global)
  

For a single function

  function strictFunction() {
    "use strict";
    // strict code here
}
  

ES modules (import/export) are automatically in strict mode.

What Strict Mode Changes

1. No accidental globals

  "use strict";
mistypedVariable = 42; // ReferenceError in strict mode
// Without strict mode, this creates a global variable
  

2. Assignment to read-only properties fails

  "use strict";
NaN = 1; // TypeError
undefined = 1; // TypeError
  

3. Duplicate parameter names are errors

  "use strict";
function sum(a, a) { // SyntaxError
    return a + a;
}
  

4. delete on non-configurable properties throws

  "use strict";
delete Object.prototype; // TypeError
  

5. eval does not create variables in surrounding scope

  "use strict";
eval("var x = 1");
console.log(typeof x); // 'undefined' (x is scoped to eval)
  

6. this is undefined in plain functions

  "use strict";
function showThis() {
    console.log(this); // undefined (not the global object)
}
showThis();
  

When to Use Strict Mode

  • Always in new projects — use modules or "use strict" at file top
  • Helps catch typos, silent failures, and unsafe patterns early
  • Required for some modern features and optimizations

Example

  "use strict";

function divide(a, b) {
    if (b === 0) {
        throw new Error('Division by zero');
    }
    return a / b;
}

let result = divide(10, 2);
console.log(result); // 5
  

Strict mode makes JavaScript more predictable and is considered a best practice for all new code.