Introduction
The strict mode of JavaScript prevents accidental global variable declarations and improves code quality by catching errors earlier in the development process.
For large projects and codebases, using use strict
is recommended as a best practice because it can help catch potential errors and improve the security and reliability of your code.
Examples
Here are two examples of how use strict
can enforce stricter coding practices and catch potential errors early in JavaScript:
Variables must be declared before use
Using a variable without explicitly declaring it will throw an error in strict mode.
For example, without “use strict”:
x = 10;
console.log(x);
This code will run without an error and return the expected result of 10.
Let’s add use strict
at the start of the code and check the results.
"use strict";
x = 10;
console.log(x);
The same code will now throw an error because x
has not been declared.
Read-only properties
In strict mode, changing the value of a read-only property will result in an error.
For example, without use strict
:
let obj = {};
Object.defineProperty(obj, 'prop', {
value: 42,
writable: false
});
obj.prop = 43;
console.log(obj.prop);
The preceding code will run without error and return the expected output of value
.
However, if we add use strict
to the start of the code, it will throw an error.
'use strict';
let obj = {};
Object.defineProperty(obj, 'prop', {
value: 42,
writable: false
});
obj.prop = 43;
// Uncaught TypeError
console.log(obj.prop);