Strict mode
Early versions of JavaScript forgave many mistakes: a typo in a variable name silently created a new variable, and a failed write to a property was simply ignored. So as not to break old websites, this behaviour was kept, but strict mode was added — a variant of the language in which such mistakes become real errors.
Turning strict mode on
Strict mode is turned on by the line 'use strict'; at the very beginning of a file or a function. It is not a command but a directive — an instruction for the JavaScript engine:
'use strict';
console.log('Strict mode is on'); // Strict mode is onIn this lesson's examples the directive is the first line, so it applies to the whole example.
Typos in names
Without strict mode, assigning to an undeclared variable creates a new global variable. The typo goes unnoticed:
let count = 0;
conut = 5;
console.log(count); // 0In strict mode the same typo immediately throws a ReferenceError:
'use strict';
let total = 0;
try {
totl = 10;
} catch (error) {
console.log(error.name); // ReferenceError
}this in a plain function
In normal mode a function called without an object gets the global object as this — and may accidentally damage something in it. In strict mode this is undefined:
'use strict';
function whoAmI() {
return this;
}
console.log(whoAmI()); // undefinedWriting to protected properties
Writing to a frozen object or to a read-only property is normally ignored silently. Strict mode reports it as an error:
'use strict';
const config = Object.freeze({ currency: '€' });
try {
config.currency = '$';
} catch (error) {
console.log(error.name); // TypeError
}Forbidden syntax
Some outdated constructs are banned outright in strict mode, and code with them will not even start — you get a SyntaxError. For example, duplicate parameter names:
'use strict';
function sum(a, a) {
return a + a;
}The with statement and numbers with a leading zero such as 010 are banned too.
Where strict mode is on by itself
You do not always need to write the directive. Module code (files with import and export) and class bodies always run in strict mode:
class Counter {
reset() {
try {
resetValue = 0;
} catch (error) {
console.log(error.name);
}
}
}
new Counter().reset(); // ReferenceErrorIn modern projects almost all code is modules, so strict mode is on there by default.
Common mistake
Putting 'use strict' somewhere other than the start. The directive works only if it is the first statement of a file or a function; otherwise it is just a string that does nothing:
console.log('Start'); // Start
'use strict';
function whoAmI() {
return this === undefined;
}
console.log(whoAmI()); // false