What does strict mode change, and how do you enable it?
Strict mode is a set of rules that you can switch on to remove the old loose behaviour from the language. You switch it on with a directive at the top of a file or at the top of a function body. The directive is the text use strict, alone in the statement position. Strict mode also applies on its own to every ES module, to the body of every class, and to the code inside every class method, so you do not need to write the directive in those places.
'use strict';
function report() {
try {
undeclared = 2; // ReferenceError in strict mode
} catch (err) {
console.log('strict mode:', err.name);
}
}
report();
const frozen = Object.freeze({ a: 1 });
try {
frozen.a = 2; // TypeError in strict mode
} catch (err) {
console.log('frozen write:', err.name);
}
The changes fall into three groups. Assigning to a variable that was never declared throws an error instead of quietly creating a global. Writing to a property that cannot be written, such as an object that has been frozen, throws an error instead of failing quietly. And a set of syntax that was once tolerated, such as old octal numbers or the same parameter name used twice, becomes a parse-time error.
There are also changes to behaviour that are harder to notice. Deleting a property becomes an error when that property cannot be deleted. Arguments and parameters stop pointing at the same place, so changing a parameter no longer changes the matching argument. And the this value inside a plain function is no longer turned into the global object, which is the change most likely to break existing code when you switch a file over.
Why it matters in practice is simple. Strict mode turns a whole family of silent failures into loud errors that a test suite or a type checker can catch. It also lets the engine make stronger optimisations, because the engine no longer has to support the old loose behaviour.