How to use strict mode

Enable strict mode in a script

Place the directive before other statements. Strict mode turns some silent mistakes into errors.

"use strict";

let score = 10;
score += 5;
console.log(score);

Catch accidental globals

Without strict mode, assignment to an undeclared name could create a global in classic browser scripts. Strict mode reports the mistake.

"use strict";

userName = "Ada";
// ReferenceError: userName is not defined

Understand module behavior

JavaScript modules are strict automatically, in browsers and Node.js. You do not need the directive inside an ES module.

// math.js (an ES module)
export function square(number) {
  return number * number;
}

Pair strict mode with modern habits

  • Declare every binding with const or let
  • Prefer modules for new projects
  • Do not depend on legacy implicit globals
  • Remember that strict mode detects some mistakes, not incorrect business logic