Skip to content
jshacks.dev
Fundamentals

Strict Mode in JavaScript and Whether You Still Need It

Strict mode turns silent mistakes into errors and is already on in ES modules and classes. See what it changes and when to add the directive.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, Node.js and TypeScript logos.

Strict mode was added in ES5 so that the language could get stricter without breaking the millions of pages already written. The old behavior stayed available as "sloppy mode", and strict mode became an opt-in. Fifteen years later, most JavaScript runs in strict mode without anyone asking, because modules and classes imply it. The question is no longer whether to use it, but how to tell which mode you are in, and what changes if you are not. This post shows the differences with output from Node.js 24, using a function constructor to reach sloppy mode from inside a module, and lists the places the directive is still needed. The mistakes it catches overlap with the scope rules and the this rules in the post on the this keyword.

How a file becomes strict

A file or function is strict in three cases. It begins with the directive "use strict". It is an ES module. Or it is inside a class body. Everything nested inside inherits the mode.

JavaScript
function sloppyOrStrict() {
  return this === undefined ? "strict" : "sloppy";
}

console.log(sloppyOrStrict());

const viaConstructor = new Function("return this === undefined ? 'strict' : 'sloppy'");
console.log(viaConstructor());

const withDirective = new Function("'use strict'; return this === undefined ? 'strict' : 'sloppy'");
console.log(withDirective());

class Example {
  static mode() {
    return (function () {
      return this === undefined ? "strict" : "sloppy";
    })();
  }
}

console.log(Example.mode());
Text
strict
sloppy
strict
strict

The first function is in an ES module, so it is strict. A function built with the Function constructor does not inherit the surrounding mode, so it is sloppy, which makes it a convenient way to compare the two in one file. Adding the directive inside makes it strict. And a plain function inside a class body is strict without any directive. In Node.js, a file ending in .cjs, or a .js file in a package without "type": "module", is CommonJS and is sloppy unless it starts with the directive.

Assigning to an undeclared name

In sloppy mode, assigning to a name that was never declared creates a global variable. A typo in a variable name becomes a new global, and nothing complains.

JavaScript
const sloppy = new Function("totl = 10; return typeof totl;");
console.log(sloppy());
console.log(typeof totl);

const strict = new Function("'use strict'; totl2 = 10;");

try {
  strict();
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
number
number
ReferenceError: totl2 is not defined

The sloppy function silently created a global named totl, and the global exists afterward. The strict version throws a ReferenceError. This single change removes a large family of bugs, such as a loop counter written without a declaration that leaks and collides with another loop.

Silent failures become errors

A sloppy program that writes to a read-only property, a frozen object or a getter-only property does nothing and carries on. A strict program throws a TypeError.

JavaScript
const settings = Object.freeze({ mode: "light" });
const account = {
  get balance() {
    return 100;
  },
};

const sloppyWrite = new Function("settings", "account", `
  settings.mode = "dark";
  account.balance = 5;
  return [settings.mode, account.balance];
`);

console.log(sloppyWrite(settings, account));

const strictWrite = new Function("settings", "account", `
  "use strict";
  settings.mode = "dark";
`);

try {
  strictWrite(settings, account);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
[ 'light', 100 ]
TypeError: Cannot assign to read only property 'mode' of object '#<Object>'

In sloppy mode both writes were discarded and the code carried on believing it had succeeded. In strict mode the first write throws with a message naming the property. If you have frozen an object to protect it, strict mode is what tells you when something tried to change it.

this in plain function calls

A function called without an object has no receiver. In sloppy mode this falls back to the global object, which makes a forgotten receiver edit a global. In strict mode it is undefined, and using it throws on the first property access.

JavaScript
const user = {
  name: "Ada",
  greet() {
    return "hello " + this.name;
  },
};

const detached = user.greet;

try {
  console.log(detached());
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const sloppyDetached = new Function("return 'this is globalThis: ' + (this === globalThis);");
console.log(sloppyDetached());
Text
TypeError: Cannot read properties of undefined (reading 'name')
this is globalThis: true

The strict case fails immediately, at the call, with a clear message. The sloppy case returns without complaint, and this is the global object, so this.name would read a global called name and return undefined. Strict mode turns the lost-receiver bug from a wrong value into an exception.

Other changes worth knowing

A handful of smaller rules complete the list.

JavaScript
const checks = {
  duplicateParams: "function f(a, a) { return a; }",
  octalLiteral: "return 010;",
  deleteName: "var x = 1; delete x;",
  withStatement: "with ({}) {}",
  reservedWord: "var static = 1;",
};

for (const [label, body] of Object.entries(checks)) {
  let sloppy = "ok";
  let strict = "ok";

  try {
    new Function(body);
  } catch (error) {
    sloppy = error.name;
  }

  try {
    new Function("'use strict';" + body);
  } catch (error) {
    strict = error.name;
  }

  console.log(label.padEnd(16), sloppy.padEnd(7), strict);
}
Text
duplicateParams  ok      SyntaxError
octalLiteral     ok      SyntaxError
deleteName       ok      SyntaxError
withStatement    ok      SyntaxError
reservedWord     ok      SyntaxError

Each row shows the outcome in sloppy mode and then in strict mode. Duplicate parameter names, octal literals, deleting a plain variable, the with statement and several reserved words are all syntax errors under strict mode, and legal in sloppy. They are old features that were either ambiguous or made optimization hard, and the strict variant removes them so engines can assume a simpler language.

Another change is that arguments stops being linked to the named parameters.

JavaScript
const sloppyArgs = new Function("a", "arguments[0] = 99; return a;");
const strictArgs = new Function("a", "'use strict'; arguments[0] = 99; return a;");

console.log(sloppyArgs(1));
console.log(strictArgs(1));
Text
99
1

In sloppy mode, writing to arguments[0] changed a as well, which defeats a reader's expectations and blocks optimizations. In strict mode they are independent copies. Code that depends on the aliasing is rare and would rather be rewritten.

Where the directive is still needed

The three cases where you must add "use strict" yourself are classic browser scripts, CommonJS files in Node.js and the output of tools that concatenate files. In all of them, the directive must be the first statement of the file or function, or it is ignored, since a directive after other code is only a string expression.

JavaScript
console.log("no effect below");
"use strict";
undeclaredAfterDirective = 1;
console.log(typeof undeclaredAfterDirective);

In a sloppy file, that program prints number, because the directive was not at the top. If the code is in an ES module, it is strict regardless and throws at the assignment. TypeScript emits the directive for you when alwaysStrict is on, which the strict option enables, so a TypeScript project compiled to CommonJS gets it without extra work. The simplest fix for most projects is to use ES modules and never think about it.

A function that has default values, rest parameters or destructuring in its parameter list cannot contain its own directive, because the engine would have to decide whether the defaults ran in strict mode before it knew the body asked for it. The rule is old and the workaround is easy.

JavaScript
try {
  new Function("a = 1", "'use strict'; return a;");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list

Put the directive at file level and the problem does not arise.

Strict mode and the rest of your toolchain

Linters and compilers overlap with strict mode, and knowing which one reports a problem helps you place the fix. A missing declaration is caught by ESLint's no-undef before the code runs, and by TypeScript as a "cannot find name" error, so in a typed project strict mode is the last line of defense and rarely the first. Writes to read-only properties are caught by TypeScript for readonly fields and as const data, and by strict mode at runtime for the cases the compiler cannot see, such as a frozen object that came from a library. A lost this is flagged by TypeScript's noImplicitThis, which is part of strict. Together they cover most of what the directive does, which is why teams that use TypeScript and ES modules seldom write the directive at all. The runtime check remains worth having for data that arrives from outside, as the post on the temporal dead zone shows for a related error.

Where sloppy mode still hides

Legacy code in an old codebase may depend on sloppy behavior: a function that reads this.something where this is the global, a name assigned without a declaration that other files read, or an arguments alias. When you convert such a file to a module, the first run will turn each of those into an error. That is the benefit, and the work: fix each at the source and keep the file strict.

Do not enable the directive file by file in a large untested codebase and expect no change. Add tests around the code first, or convert one module at a time and run the suite between each.

The semantics are defined in the specification under strict mode code, and MDN's strict mode page lists every change.

Taggedbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.