JavaScript Strict Mode

Strict mode is a way to opt into a restricted variant of JavaScript that catches common coding errors and unsafe actions. Enabled with the "use strict" directive, it makes JavaScript more secure, prevents silent errors, and prohibits features likely to cause bugs.

Strict Mode Rules

The "use strict" directive must appear at the very beginning of a script or function, before any other statements. Placing it mid-script has no effect. "use strict"; at the top of a file enables strict mode for the entire script. Inside a function, it enables strict mode only for that function. Most modern JavaScript code uses strict mode globally.

In strict mode, all variables must be explicitly declared with var, let, or const. Accidentally creating globals by assigning to undeclared variables (x = 5) throws an error instead of silently creating a global. This catches a common source of bugs where typos in variable names create unintended globals.

Deleting variables, functions, or function parameters is not allowed in strict mode. delete myVariable throws an error. delete only works on object properties, not variables. This prevents accidentally deleting variables and ensures the delete operator is used correctly.

Duplicate parameter names in functions are not allowed. function test(a, a) {} throws a syntax error in strict mode. This prevents confusion about which parameter is being referenced and catches copy-paste errors where parameters are accidentally duplicated.

Octal numeric literals (numbers starting with 0 like 0123) are not allowed. They're a confusing feature from early JavaScript. In strict mode, 0123 is a syntax error. Use 0o prefix for octal (0o123) or just write decimal numbers. This prevents accidental octal interpretation of numbers with leading zeros.

In strict mode, this is undefined in regular function calls, not the global object. function test() { console.log(this); } shows undefined in strict mode, not window. This prevents accidentally modifying global objects and makes this behavior more predictable. Methods still have this pointing to their object.

"use strict";

// Must declare variables
// x = 3.14; // Error!
let x = 3.14; // OK

// Cannot delete variables
let y = 5;
// delete y; // Error!

// Function strict mode
function strictFunction() {
  "use strict";
  // Strict mode only in this function
  // z = 10; // Error!
}

// this is undefined
function showThis() {
  "use strict";
  console.log(this); // undefined
}

// No duplicate parameters
// function test(a, a) {} // Error in strict!