Codectionary / Developer documentation / JavaScript

Strict Mode

"use strict" opts your code into a restricted variant of JavaScript that catches common mistakes by turning them into errors - like accidentally creating a global variable by forgetting to declare it. ES6 modules and classes are automatically in strict mode, so most modern code benefits from it without explicitly writing the directive.

Syntax

"use strict";

Examples

Catching Accidental Globals

Strict mode throws an error instead of silently creating a global variable.

"use strict";

try {
  undeclaredVariable = 5; // ReferenceError in strict mode
} catch (e) {
  console.log(e.message);
}

// Without strict mode, this would silently create a global variable - a common bug source

Strict Mode is Automatic in Modules and Classes

You often get strict mode benefits without writing the directive at all.

// In an ES module file, this is automatic:
export function myFunction() {
  // strict mode is already active here
}

class MyClass {
  // class bodies are always strict mode, even outside modules
}

Best practices

  • If writing plain scripts (not modules), add "use strict" at the top of the file or function to catch silent errors
  • Remember ES6 modules (using import/export) and class bodies are strict mode by default - no directive needed
  • Treat strict mode errors as bugs to fix, not obstacles to work around, since they usually reveal a genuine mistake
  • Avoid mixing strict and non-strict code within the same file where possible, for consistent behavior

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation