What does "use strict" do in JavaScript and why should you enable it? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What does "use strict" do in JavaScript and why should you enable it?

message-square
0

To enable strict mode in JavaScript, place the exact directive "use strict"; at the top of a script or at the very beginning of a function body—though ES modules (<script type="module"> or import/export) and JavaScript class bodies already run in strict mode automatically. Enabling strict mode turns silent runtime mistakes and legacy quirks into explicit errors, prevents accidental global variable creation, disallows duplicate function parameter names, blocks with statements, and sets this to undefined inside plain functions called without a receiver instead of coercing to the global object (window / globalThis).


1. Core Behavioral Changes and Error Prevention

Strict mode catches bugs at parse or execution time that sloppy mode quietly ignores, while improving engine optimization predictability:

// Strict mode prevents accidental globals and catches invalid assignments early
"use strict";

function calculateNetPrice(basePrice, taxRate) {
  if (typeof basePrice !== "number" || !Number.isFinite(basePrice)) {
    throw new TypeError("Expected basePrice to be a finite number.");
  }
  if (typeof taxRate !== "number" || !Number.isFinite(taxRate)) {
    throw new TypeError("Expected taxRate to be a finite number.");
  }

  // In sloppy mode, an undeclared variable like `total = ...` would create a global!
  // In strict mode, assigning to an undeclared identifier throws ReferenceError.
  const total = basePrice * (1 + taxRate);
  return Number(total.toFixed(2));
}

function showReceiver() {
  // In strict mode, plain function calls have `this === undefined` (not globalThis)
  return this;
}

try {
  console.log(calculateNetPrice(100, 0.18)); // 118
  console.log(showReceiver());              // undefined
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}
  • No accidental globals: Writing to an undeclared variable throws a ReferenceError instead of silently creating a property on the global object.
  • Safer this binding: Standalone function calls receive undefined rather than window or globalThis, helping catch detached method calls early.

2. Syntax Restrictions That Eliminate Subtle Bugs

Strict mode rejects several older JavaScript constructs that cause hard-to-trace logic errors or prevent reliable lexical optimization:

// Examples of rules enforced in strict mode (shown safely via dynamic evaluation)
function checkStrictSyntaxRules() {
  const checks = [
    {
      rule: "Duplicate parameter names",
      code: '"use strict"; function dup(a, a) { return a; }'
    },
    {
      rule: "Octal integer literals",
      code: '"use strict"; const n = 0755;'
    },
    {
      rule: "Deleting plain variables or non-configurable properties",
      code: '"use strict"; const obj = {}; Object.defineProperty(obj, "x", { value: 1, configurable: false }); delete obj.x;'
    }
  ];

  return checks.map(({ rule, code }) => {
    try {
      // Using Function constructor isolates parse/runtime errors cleanly
      new Function(code);
      return { rule, threw: false, error: null };
    } catch (error) {
      return { rule, threw: true, error: `${error.name}: ${error.message}` };
    }
  });
}

console.log(checkStrictSyntaxRules());
  • No duplicate parameter names: Prevents later identical parameter names from silently shadowing earlier ones.
  • No with statement: Eliminates scope ambiguity where identifier lookup could resolve to either an object property or a lexical variable.

3. Modules, eval, and Placement Gotchas

When adding "use strict"; manually to non-module scripts or individual functions, place it before any executable statements—any statement (even a comment is fine, but real code is not) preceding "use strict"; causes the directive to be treated as an ordinary string literal with no effect:

// Function-scoped strict mode (useful in mixed legacy script files)
function processBatch(items) {
  "use strict";

  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  const results = [];
  for (let i = 0; i < items.length; i += 1) {
    results.push(String(items[i]).trim());
  }
  return results;
}

console.log(processBatch(["  alpha ", " beta  "])); // ["alpha", "beta"]
  • ES modules are already strict: You do not need "use strict"; at the top of native ES modules (import/export) or class declarations/expressions.
  • Watch out when concatenating scripts: Putting "use strict"; at the top of a single file forces every concatenated script in that bundle into strict mode, which can break legacy sloppy-mode scripts if any depend on non-strict behavior.