Chapters

FundamentalsChapter 21 of 21

Strict Mode

The safer dialect, why it exists, and where you already have it.

What it is

Strict mode is a slightly different, stricter dialect of JavaScript. It turns several silent mistakes into errors and removes a few features that were mistakes.

JavaScript

JavaScript

'use strict';

try {
  undeclared = 5;
} catch (error) {
  console.log(error.name + ': ' + error.message);
}

Output

ReferenceError: undeclared is not defined

Without strict mode that line creates a global variable and carries on, which is how a typo in one function ends up changing something on the other side of a program.

What changes

  • Assigning to an undeclared name throws instead of creating a global.
  • Assigning to a read-only or frozen property throws instead of failing quietly.
  • this is undefined in a plain function call rather than the global object.
  • Duplicate parameter names are a syntax error.
  • Octal literals written as 010 are a syntax error.
  • delete on a plain variable is a syntax error.
JavaScript

JavaScript

'use strict';

const frozen = Object.freeze({ a: 1 });

try {
  frozen.a = 2;
} catch (error) {
  console.log(error.name);
}

Output

TypeError

Outside strict mode that assignment does nothing at all and reports no problem, which is considerably worse than an error.

Where you already have it

You rarely need to write the directive today, because the places modern code lives are strict already.

ContextStrict?
ES module (type="module", or any import)always
Class bodyalways
Ordinary scriptonly with the directive
Function with the directive at the topthat function only

Writing the directive

It must be the very first statement in the file or function, written as a plain string. Anything above it, including a stray semicolon, silently turns it off.

JavaScript

JavaScript

// Works: first line of the file.
'use strict';

// Does nothing: something came first.
const ready = true;
'use strict';

Note

Because it is just a string, an engine that never supported strict mode ignores it harmlessly. That is why the feature was designed this way.

Test yourself

2 questions

What happens in strict mode when you assign to a name you never declared?

Show the answer

A ReferenceError Without strict mode it creates a global, which turns a typo into a bug somewhere else entirely.

Which context is strict without any directive?

Show the answer

An ES module Modules and class bodies are always strict, which is why the directive is rarely written now.