Strict Mode
Strict Mode is a feature in JavaScript that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.
1. Enabling Strict Mode
To enable strict mode, you add the string "use strict"; to the beginning of a script or a function.
Global Scope
Applies to the entire script.
"use strict";
x = 3.14; // ReferenceError: x is not defined
Function Scope
Applies only within that function.
x = 3.14; // No error (non-strict)
function myStrictFunction() {
"use strict";
y = 3.14; // ReferenceError: y is not defined
}
2. Key Changes
1. Converting Mistakes into Errors
In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this throws an error.
"use strict";
mistypedVaraible = 17; // Throws ReferenceError
2. this in Functions
In non-strict mode, if a function is called as a simple function call, this defaults to the global object (window). In strict mode, this is undefined.
"use strict";
function f() {
return this;
}
console.log(f() === undefined); // true
3. No Duplicate Parameter Names
Strict mode forbids duplicate parameter names in functions.
function sum(a, a, c) { // SyntaxError in strict mode
"use strict";
return a + a + c; // Wrong logic if allowed
}
4. Eliminating with
The with statement is prohibited in strict mode because it makes scope lookups ambiguous and slows down compilation.
5. Writing to Read-Only Properties
Assigning values to non-writable properties throws an error.
"use strict";
const obj = {};
Object.defineProperty(obj, "x", { value: 42, writable: false });
obj.x = 9; // TypeError
3. Why use it?
- Fail Fast: It catches common coding bloopers, throwing exceptions instead of silently failing or behaving weirdly.
- Security: It prevents access to the global object in some cases.
- Optimization: Strict mode code can sometimes be made to run faster than identical code that's not strict mode.
- Future Proofing: It prohibits some syntax likely to be defined in future versions of ECMAScript.
Note: ES6 Modules and Classes are in strict mode by default.
programming/javascript/vanilla/javascript programming/javascript/vanilla/this-keyword programming/javascript/vanilla/es6-vs-commonjs