Strict Mode

An opt-in restricted variant of JavaScript that turns several silent mistakes into thrown errors.

                'use strict';
              

Purpose

Strict mode is a restricted variant of JavaScript that catches common mistakes by throwing errors instead of silently doing something unexpected. It’s opt-in in plain scripts, but on by default in two very common places.

Syntax

'use strict';
// entire script is strict from here on

function example() {
  'use strict';
  // only this function is strict
}

The directive must be the first statement in a script or function body (comments and other directives may precede it) β€” written anywhere else, it’s just an unused string literal.

Where strict mode is already on

  • Inside any ES module (any file loaded via import/export).
  • Inside any class body.

Both of these are strict without writing 'use strict' yourself. Plain scripts and traditional function declarations outside a module are not strict unless you opt in.

Behavior

Strict mode changes several things that would otherwise fail silently:

'use strict';

undeclaredVariable = 5;
// Uncaught ReferenceError: undeclaredVariable is not defined
// (without strict mode, this silently creates a global variable instead)
  • Assigning to an undeclared name throws a ReferenceError instead of creating an accidental global.
  • Assigning to a read-only or non-writable property throws a TypeError instead of failing silently.
  • Duplicate parameter names (function f(a, a) {}) are a SyntaxError.
  • Inside a plain function called without an object (someFunction(), not obj.someFunction()), this is undefined rather than silently becoming the global object.

Common mistakes

  • Assuming a modern codebase needs an explicit 'use strict' β€” if every file is an ES module (the default for most current tooling), it’s redundant; modules are already strict.
  • Placing the directive after other code β€” it only takes effect as the very first statement.

Runtime notes

Strict mode is part of the ECMAScript standard, so its behavior is identical in browsers and Node.

Taught in these lessons

Related reference