Strict Mode
Strict mode is a stricter version of JavaScript that turns several silent mistakes into errors and forbids a few confusing features. It is switched on by the directive 'use strict'; as the first statement of a script or a function. Code without it runs in what is informally called sloppy mode.
Strict mode was added in ES5 so that the language could fix old mistakes without breaking existing pages, which is why it has to be requested. ES modules and the bodies of classes are always strict, with no directive needed, so most modern code already runs in strict mode. The directive still matters in classic <script> files and in Node.js CommonJS files, which are sloppy unless they ask.
The examples run as CommonJS files in Node.js, which start in sloppy mode just as a browser’s classic scripts do.
Switching it on
Section titled “Switching it on”The directive must come before any other statement, though comments may precede it. At the top of a file, it applies to the whole file. At the top of a function, it applies to that function and to any functions inside it.
'use strict';
// the rest of the file is strictPlaced anywhere else, the line is just a string that does nothing. Joining several script files into one, as older build tools did, can also move a directive away from the top and switch it off without warning.
Undeclared variables
Section titled “Undeclared variables”In sloppy mode, assigning to a name that was never declared creates a new global variable. A typing mistake therefore goes unnoticed, and the intended variable keeps its old value. Strict mode throws a ReferenceError instead.
function strictTotal() { 'use strict'; let subtotal = 0; subtotl = 40; return subtotal;}
function sloppyTotal() { let subtotal = 0; subtotl = 40; return subtotal;}
try { strictTotal();} catch (err) { console.log(`${err.name}: ${err.message}`);}
console.log(sloppyTotal(), globalThis.subtotl);This prints:
ReferenceError: subtotl is not defined0 40The sloppy function returns 0 because the value went into a new global called subtotl. Global Variables and globalThis covers the global object.
Failed assignments throw
Section titled “Failed assignments throw”In sloppy mode, an assignment that cannot happen is ignored without an error. This includes writing to a read-only property, adding a property to a frozen or sealed object, and deleting a property that cannot be deleted.
const book = Object.freeze({ title: 'Emma', pages: 474 });book.pages = 500;book.edition = 2;delete book.title;console.log(book);This prints:
{ title: 'Emma', pages: 474 }None of the three changes happened, and nothing said so. In strict mode, each one throws a TypeError:
'use strict';
const book = Object.freeze({ title: 'Emma', pages: 474 });const attempts = [ () => { book.pages = 500; }, () => { book.edition = 2; }, () => { delete book.title; },];
for (const attempt of attempts) { try { attempt(); } catch (err) { console.log(`${err.name}: ${err.message}`); }}This prints:
TypeError: Cannot assign to read only property 'pages' of object '#<Object>'TypeError: Cannot add property edition, object is not extensibleTypeError: Cannot delete property 'title' of #<Object>The same applies to read-only globals, so NaN = 1 and undefined = 1 throw in strict mode, as does assigning to a property that has a getter but no setter. Seal, Freeze and PreventExtensions and Property Descriptors explain how properties become read-only.
this in a plain function call
Section titled “this in a plain function call”When a function is called on its own, not as a method, sloppy mode sets this to the global object, whereas strict mode leaves it undefined.
function sloppyThis() { return this === globalThis;}
function strictThis() { 'use strict'; return this;}
console.log(sloppyThis());console.log(strictThis());This prints:
trueundefinedThis turns a lost this into an immediate error. A method copied out of its object and called on its own fails as soon as it reads a property of this, instead of quietly reading and writing global variables.
Code that will not run at all
Section titled “Code that will not run at all”Some code is a SyntaxError in strict mode, so the whole script fails to load rather than failing when the line runs:
- a function with two parameters of the same name, such as
function average(a, b, a) - the
withstatement - old-style octal numbers with a leading zero, such as
010, where0o10is the form to use deleteapplied to a plain variable name, such asdelete total- variables called
evalorarguments, and words reserved for future use, such aslet,static,implements,interface,package,private,protectedandpublic
Strict mode also stops eval() from creating variables in the surrounding scope, and in a strict function the arguments object no longer changes when a parameter is reassigned.
None of this changes how let, const and var behave. Reassigning a let variable is allowed in both modes, and reassigning a const throws a TypeError in both. The MDN page on strict mode lists every difference.
Steve Griffith covers this topic in his video Using JavaScript Strict Mode.