JavaScript Strict Mode
JavaScript Use Strict
Section titled “JavaScript Use Strict”"use strict"; is a directive that enables “strict mode” in JavaScript. Strict mode changes how JavaScript code is executed, making it more robust by catching common coding errors and preventing or throwing errors for certain “unsafe” actions.
The "use strict" Directive
Section titled “The "use strict" Directive”The "use strict" directive was introduced in ECMAScript 5 (ES5).
It’s not a statement, but a literal expression. Older JavaScript engines that don’t support strict mode will simply ignore it.
The purpose of "use strict" is to opt into a restricted variant of JavaScript, often referred to as “strict mode”.
In strict mode, for example, you cannot use undeclared variables, which helps prevent accidental global variable creation.
| Strict mode is widely supported in all modern browsers (IE10+, Firefox 4+, Chrome 13+, Safari 5.1+, Opera 12+) and Node.js. |
|---|
Declaring Strict Mode
Section titled “Declaring Strict Mode”Strict mode is declared by adding "use strict"; at the beginning of a script or a function.
1. Global Scope (Script-wide):
Section titled “1. Global Scope (Script-wide):”When declared at the beginning of a script file, strict mode applies to the entire script.
// In a script file (e.g., myscript.js)"use strict";
// let x = 3.14; // This is fine because x is declared// y = 3.14; // This would cause a ReferenceError because y is not declared
// function myFunction() {// // This function is also in strict mode// // z = 3.14; // ReferenceError// }// myFunction();2. Function Scope (Local):
Section titled “2. Function Scope (Local):”When declared at the beginning of a function body, strict mode applies only to the code within that function.
// x = 3.14; // This might be okay if not in strict mode globally, or might create a global variable
// function strictFunction() {// "use strict";// // This function is in strict mode// // y = 3.14; // ReferenceError// let z = 3.14; // OK// }// strictFunction();
// function nonStrictFunction() {// // This function is NOT in strict mode (unless the whole script is)// // w = 3.14; // Might create a global or be an error depending on outer scope// }// nonStrictFunction();Important Note for Modern JavaScript:
JavaScript modules (using <script type="module"> in HTML, or ES module syntax in Node.js) are automatically in strict mode. You don’t need to add "use strict"; in modules.
Code inside ES6 classes is also always in strict mode.
Why Use Strict Mode?
Section titled “Why Use Strict Mode?”- Catches common coding mistakes: Turns silent errors into thrown errors (e.g., assigning to undeclared variables).
- Prevents “unsafe” actions: Forbids actions like writing to read-only global properties or deleting non-configurable properties.
- Disables confusing or poorly thought-out features: Removes or alters features like
withstatement and octal literals with leading zeros. - Simplifies variable resolution: Makes it easier for developers and JavaScript engines to understand variable scope.
- Secures
eval(): Variables and functions declared insideeval()in strict mode do not pollute the surrounding scope. - Changes
thisbinding: In functions called without an explicit context (not as methods or constructors),thisisundefinedinstead of the global object. This prevents accidental modification of globals. - Prepares for future ECMAScript versions: Forbids syntax that might be used in future versions (e.g., certain reserved words).
Key Changes and Restrictions in Strict Mode
Section titled “Key Changes and Restrictions in Strict Mode”- Undeclared Variables:
Assigning to an undeclared variable throws a ReferenceError (prevents accidental global creation).
// "use strict";// undeclaredVar = 10; // ReferenceError- Deleting Variables, Functions, or Arguments:
Using delete on a variable name, function name, or argument name throws a SyntaxError.
// "use strict";// let x = 3.14;// delete x; // SyntaxError
// function myFunction(arg) {// delete arg; // SyntaxError// }// delete myFunction; // SyntaxError- Duplicate Property Names or Parameter Names:
Duplicate property names in an object literal or duplicate parameter names in a function definition are a SyntaxError.
// "use strict";// const obj = { p1: 10, p1: 20 }; // SyntaxError// function sum(a, a) {} // SyntaxError- Octal Syntax:
Octal numeric literals with a leading zero (e.g., 010) are a SyntaxError. Use the modern 0o prefix (e.g., 0o10). Octal escape sequences in strings (e.g., "\010") are also forbidden.
// "use strict";// const octalNum = 010; // SyntaxError// const octalStr = "\010"; // SyntaxError (in some contexts)// const modernOctal = 0o10; // OK, value is 8- Writing to Read-Only or Non-Writable Properties:
Assigning to a non-writable property, a getter-only property, or a non-existing property on a non-extensible object throws a TypeError.
// "use strict";// const obj = {};// Object.defineProperty(obj, "x", { value: 0, writable: false });// obj.x = 3.14; // TypeError
// const obj2 = { get y() { return 0; } };// obj2.y = 3.14; // TypeError- Deleting Non-Configurable Properties:
Attempting to delete a non-configurable property throws a TypeError.
// "use strict";// delete Object.prototype; // TypeErrorevalandargumentsas Identifiers:
The strings eval and arguments cannot be used as variable names, function names, parameter names, or labels.
// "use strict";// let eval = 3.14; // SyntaxError// let arguments = "test"; // SyntaxError- The
withStatement:
The with statement is a SyntaxError in strict mode.
// "use strict";// with (Math) { x = cos(2); } // SyntaxErroreval()Scope:
Variables and functions declared inside eval() code are not created in the surrounding scope (they are created in a new scope for the eval call).
// "use strict";// eval("let newVar = 2;");// console.log(typeof newVar); // "undefined" (newVar is not in this scope)thisin Functions:
In functions invoked without a specific context (e.g., myFunc() instead of obj.myFunc() or new MyFunc()), this is undefined (instead of the global object in non-strict mode).
// "use strict";// function showThis() {// console.log(this); // undefined// }// showThis();arguments.calleeandarguments.caller:
Accessing arguments.callee (refers to the enclosing function) or arguments.caller (refers to the function that called the enclosing function) throws a TypeError.
- Reserved Keywords:
Using future reserved keywords (like implements, interface, let (though let is now implemented), package, private, protected, public, static, yield) as variable or function names is a SyntaxError. This helps ensure smoother transitions to future JavaScript versions.
Watch Out!
Section titled “Watch Out!”The "use strict"; directive is only recognized at the very beginning of a script or a function body. No other statements (except comments or other directives) can precede it. |
|---|
Using strict mode is highly recommended for all new JavaScript projects to write cleaner, more reliable, and more secure code.