JavaScript Strict Mode
Strict Mode is a feature in JavaScript that enables a stricter set of rules for writing code. Introduced in ECMAScript 5 (ES5), it helps developers catch common mistakes, prevents unsafe actions, and improves performance by allowing JavaScript engines to optimize code execution. Strict Mode enforces safer coding practices and reduces hard-to-debug errors, making code cleaner, more secure, and more predictable.
How to Enable Strict Mode
Strict Mode is enabled using the "use strict";
directive. It can be applied globally to the entire script or locally to individual functions.
Global Strict Mode:
Add "use strict";
at the top of your script to apply strict mode globally:
"use strict";
var x = 10; // Strict mode applied to entire script
Function-Level Strict Mode:
You can enable strict mode only inside a specific function:
function exampleFunction() {
"use strict";
var y = 20; // Strict mode applied only inside this function
}
Key Features of Strict Mode
1. Catches Common Coding Errors
Using undeclared variables throws a ReferenceError
.
"use strict";
x = 10; // ReferenceError: x is not defined
2. Prevents Accidental Globals
Variables must be declared with let
, const
, or var
.
Helps avoid unintended global variables.
3. Disallows Duplicate Parameter Names
"use strict";
function sum(a, a) {} // SyntaxError: Duplicate parameter name
4. Secures this
in Functions
In functions, this
is undefined
if called without an object context, preventing accidental global object modification.
"use strict";
function checkThis() {
console.log(this);
}
checkThis(); // undefined
5. Disallows with
Statement
The with
statement is prohibited due to unpredictable behavior.
"use strict";
with (Math) { let x = cos(2); } // SyntaxError
6. Prevents Writing to Read-Only Properties
Attempting to modify immutable properties throws a TypeError
.
"use strict";
const obj = Object.freeze({ prop: 42 });
obj.prop = 50; // TypeError
7. Prevents eval()
from Creating Variables in Surrounding Scope
Variables declared inside eval()
do not leak outside.
"use strict";
eval("var x = 10;");
console.log(x); // ReferenceError
8. Disallows Deleting Non-Configurable Properties
"use strict";
const obj = {};
Object.defineProperty(obj, "prop", { value: 10, configurable: false });
delete obj.prop; // TypeError
9. Enhances Performance Optimization
Some JavaScript engines can optimize code more effectively when Strict Mode is enabled.
Advantages of Using Strict Mode
- Safer Coding: Prevents accidental global variables, misuse of
this
, and unsafe actions. - Error Detection: Catches common errors early, making debugging easier.
- Improved Maintainability: Cleaner, predictable code that reduces runtime issues.
- Optimized Execution: Modern engines can run strict mode code more efficiently.