Strict Mode
JavaScript is known for being a forgiving language—it often allows code with minor mistakes to run instead of throwing immediate errors. While this permissiveness can be helpful in some cases, it can also make debugging and maintaining code more difficult. To address these issues and promote safer, more reliable code, JavaScript introduced strict mode, a way to enforce stricter parsing and error handling rules.
In this guide, we'll explore what strict mode is and why it matters, through the following sections:
Introduction to Strict Mode
What Is Strict Mode?
Strict mode is a special mode in JavaScript that helps catch certain errors and reduce bugs during code execution. It enforces stricter parsing and error handling on your JavaScript code. Strict mode can be enabled by adding the "use strict"
directive at the beginning of a script or function.
"use strict";
// Code running in strict mode
Purpose of Using Strict Mode
The main goal of strict mode is to improve code quality and reduce errors, creating a safer development environment. JavaScript is a flexible language that performs many implicit type conversions and error handling behaviors, which can sometimes lead to unexpected results. Strict mode clarifies these ambiguities and reduces unexpected errors, thereby increasing code reliability.
"use strict";
function exampleFunction() {
nonDeclaredVar = 10; // ReferenceError: nonDeclaredVar is not defined
}
exampleFunction();
This code example shows a function exampleFunction
written in strict mode.
"use strict"
: This directive enables strict mode within the script or function scope where it appears.function exampleFunction() { ... }
: This function runs in strict mode, so its code follows strict mode rules.nonDeclaredVar = 10;
: This line causes an error becausenonDeclaredVar
is assigned without being declared. In strict mode, using undeclared variables is prohibited.exampleFunction();
: This calls the function, executing its code.
In this example, since "use strict"
enables strict mode, attempting to assign a value to an undeclared variable inside exampleFunction
triggers a ReferenceError
. This demonstrates how strict mode helps prevent mistakes and improve code safety.
Why Use Strict Mode?
- Reduces errors and simplifies debugging: Strict mode prevents many common mistakes and runtime errors, making debugging easier during development.
- Enhances security: It helps avoid unexpected behaviors that could allow malicious code execution.
- Improves readability: By enforcing explicit variable declarations and preventing duplicate parameter names, strict mode makes code clearer.
- Encourages modern coding practices: Strict mode is an important part of modern JavaScript development, promoting better coding habits.
Enabling Strict Mode
There are several ways to enable strict mode in JavaScript:
- Using the
"use strict"
directive. - Applying strict mode to an entire script.
- Enabling strict mode within a specific function.
- Modules are strict by default.
Note:
Strict mode does not take effect inside regular block statements enclosed in curly braces ({}
).
For example, placing the "use strict"
directive inside an if
block, a for
loop, or any general-purpose block has no effect.
The Role of the "use strict"
Directive
The "use strict"
directive activates strict mode. When placed at the top of a script or function, all code within that scope runs in strict mode.
"use strict"
// Strict mode is enabled from this point onward.
Applying Strict Mode to an Entire Script
To enable strict mode for an entire script, add the "use strict"
directive at the very top of the script file. This activates strict mode throughout the whole file.
"use strict";
// Strict mode is applied throughout this file.
Enabling Strict Mode Within a Function
To enable strict mode only within a specific function, place the "use strict"
directive at the beginning of that function. Strict mode rules will apply only inside that function, without affecting other functions or scripts.
function myFunction() {
"use strict";
// Strict mode applies only within this function.
}
Modules Are Strict by Default
JavaScript modules automatically run in strict mode, so you don’t need to add the "use strict"
directive.
<script type="module">
function myStrictFunction() {
// Modules run in strict mode by default.
}
export default myStrictFunction;
</script>
How Strict Mode Works
The main differences between using strict mode and not using it in JavaScript are summarized in the table below:
Feature / Scenario | When Using Strict Mode | When Not Using Strict Mode |
---|---|---|
Implicit Globals | Using variables without declaring them causes an error. | Variables can be used without declaration without causing an error. |
Assignment to Non-writable Properties | Assigning a value to a non-extensible object property throws an error. | No error occurs when assigning to a non-extensible object property. |
Duplicate Parameter Names | Using duplicate parameter names in functions causes an error. | Duplicate parameter names are allowed without errors. |
this Value in Regular Functions |
this inside a regular function is undefined instead of the global object. |
this defaults to the global object if no call context is set. |
Implicit Globals Prohibition
Feature / Scenario | When Using Strict Mode | When Not Using Strict Mode |
---|---|---|
Implicit Globals Prohibited | Using variables without declaring them causes an error. | Using variables without declaration does not cause an error. |
"use strict"
function exampleStrict() {
strictVar = 10; // ReferenceError: strictVar is not defined
}
exampleStrict();
In the code above, attempting to use the variable strictVar
without declaring it results in a ReferenceError
in strict mode. This prevents implicit globals by enforcing explicit variable declarations.
function exampleNonStrict() {
nonStrictVar = 20; // No error, implicitly becomes a global variable
}
exampleNonStrict();
console.log(nonStrictVar); // 20
In non-strict mode, using nonStrictVar
without declaration causes no error. The variable becomes an implicit global, which can lead to unexpected behavior and bugs.
Assignment to Non-writable Properties Prohibited
Feature / Scenario | When Using Strict Mode | When Not Using Strict Mode |
---|---|---|
Assignment to Non-writable Properties Prohibited | Assigning values to properties of a sealed (non-extensible) object throws an error. | No error occurs when assigning values to sealed object properties. |
"use strict"
const sealedObject = Object.seal({ prop: 10 });
// Throws a TypeError when assigning new properties in strict mode
sealedObject.newProp = 20; // TypeError: Cannot add property newProp, object is not extensible
const nonStrictSealedObject = Object.seal({ prop: 10 });
// No error; new property is added in non-strict mode
nonStrictSealedObject.newProp = 20;
The example above uses Object.seal()
to make an object non-extensible. In strict mode, attempting to add new properties to such an object throws a TypeError
, while in non-strict mode it silently allows the addition.
Duplicate Parameter Names Prohibited
Feature / Scenario | When Using Strict Mode | When Not Using Strict Mode |
---|---|---|
Duplicate Parameter Names Prohibited | Functions with duplicate parameter names cause a syntax error. | Duplicate parameter names are allowed without error. |
"use strict"
function strictExample(param1, param1) {
console.log(param1);
}
strictExample(10, 20); // SyntaxError: Duplicate parameter name not allowed in this context
function nonStrictExample(param1, param1) {
console.log(param1);
}
nonStrictExample(10, 20);
In the strict mode example, the function strictExample
causes a SyntaxError
due to duplicate parameter names. In non-strict mode, the duplicate parameters are allowed, and the second parameter value is used.
this
Value in Regular Function Calls
Feature / Scenario | When Using Strict Mode | When Not Using Strict Mode |
---|---|---|
this Value in Regular Functions |
this is undefined inside a regular function. |
this refers to the global object when not in strict mode. |
"use strict"
function strictFunction() {
return this;
}
console.log(strictFunction()); // undefined
function nonStrictFunction() {
return this;
}
console.log(nonStrictFunction()); // Global object (window in browsers)
In strict mode, calling strictFunction
returns undefined
for this
. In non-strict mode, calling nonStrictFunction
returns the global object. Strict mode does not automatically bind this
to the global object in regular function calls.
Using Strict Mode to Improve Code Quality
Leveraging strict mode is crucial for enhancing code quality.
Reducing Mistakes and Errors to Improve Maintainability
Strict mode helps prevent and detect certain mistakes and errors in your code ahead of time. This reduces bugs during development and saves debugging time. By enforcing explicit variable declarations, preventing duplicate parameter names, and other rules, strict mode increases code stability and maintainability.
Improving Readability with Strict Mode
Strict mode also contributes to better code readability. Explicit variable declarations and initializations, as well as clear this
usage, make the code’s behavior more transparent and easier to understand.
"use strict"
// Without strict mode
var globalVar = 10;
function someFunction(x) {
y = x * 2; // Potential error: y is implicitly global
return y;
}
// With strict mode
var globalVar = 10;
function someFunction(x) {
var y = x * 2; // Explicit variable declaration
return y;
}
In the example above, using strict mode emphasizes explicit variable declaration and initialization, improving code readability.
Applying these practices helps increase both code quality and clarity. Strict mode is a valuable tool that not only reduces runtime errors and improves reliability but also clarifies the developer’s intent, making maintenance easier.
Specifications
Specification | |
---|---|
"use strict"
|
The Strict Mode of ECMAScript |
Browser compatibility
Directive |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
"use strict"
|
13 | 10 | 4 | 6 |