While JavaScript is a very versatile language, sometimes it is too easy to make mistakes while coding.
In order to solve some of these issues, ECMAScript 5 (ES5) introduced Strict Mode in 2009.
Strict Mode enforces stricter conditions on the JavaScript code and prevents common mistakes.
For instance, it will not let you create a variable unintentionally and will transform silent errors into errors.
It teaches programmers to code better.
In this tutorial, we will find out what Strict Mode is, how to activate it, and what differences there are between the normal mode and Strict Mode.
Table of Contents
What Is Strict Mode?
Strict Mode is an enhanced way to execute JavaScript code that catches potential errors JavaScript ignores in default mode.
- Appeared in ES5: Strict Mode appeared in ECMAScript 5 (ES5), in 2009, as an optional JavaScript feature.
- Different Execution, Same Syntax: Strict Mode doesn't change JavaScript syntax but affects how the code is parsed and executed.
- Errors Instead of Silent Failures: Under Strict Mode, the code will raise errors if previously such an action would be executed in a silent manner.
- No Extra Features: Strict Mode does not introduce any extra features into JavaScript; it just eliminates unsafe behaviors.
- Optional by Default: By default, JavaScript code executes in "sloppy" mode, but you can opt into Strict Mode.
// Sloppy mode (default) - no warning here
x = 10; // creates a global variable accidentally
console.log(x); // 10// Strict mode - this would throw an error instead
"use strict";
y = 10; // ReferenceError: y is not defined
How To Enable It?
Strict Mode is activated through a unique text command referred to as a directive and should be located at the top of your program or code.
- Activation of Strict Mode in Whole Script: To activate Strict Mode in an entire script/file, the text "use strict"; should appear as the first line of that script.
- Activation of Strict Mode in One Function: For activation in only one function, the text "use strict"; should appear as the first line in that particular function.
- Directive Text Format: This directive has to appear as an exact string literal ("use strict";) without any other statement appearing before it.
- Placement Is Critical: Placing "use strict"; at any place other than the beginning will make JavaScript interpret it as an inert string, and strict mode will fail to activate.
- Auto-Activate In Modules/Classes: ES6 Modules and Classes have automatic activation in strict mode; there is no need to use any directive in such cases.
Example of Enabling For Single Function:// Enabling for the whole file
"use strict";function greet() {
console.log("Hello, world!");
}
greet();
// Enabling for a single function only
function myFunction() {
"use strict";
z = 5; // ReferenceError, because this function is strict
}function normalFunction() {
a = 5; // Works fine, because this function is NOT strict
console.log(a);
}
Preventing Global Leaks
Strict Mode ensures that you will not accidentally create global variables as a result of forgetting to declare them.
- Global Variables Prevention: In loose mode, writing score = 100; without first declaring score would create an unintended global variable.
- Actual Error is Generated: In Strict Mode, this same line generates a ReferenceError, compelling the user to correctly declare their variables.
- Bug Prevention: This single feature alone prevents countless bugs from occurring, especially in large-scale projects comprising numerous files.
- More Easy-to-Debug Code: This makes debugging easier since typos in variables will generate errors instead of creating new variables.
- Promotes Best Practice: This promotes the best practice of always declaring variables using let/const.
Example of Correct Form, i.e, Property Declared Variable:"use strict";
function calculateTotal() {
total = 100; // Forgot to declare with let/const/var
return total;
}calculateTotal(); // ReferenceError: total is not defined
// Correct way with strict mode
"use strict";function calculateTotal() {
let total = 100; // properly declared
return total;
}console.log(calculateTotal()); // 100
Silent Failures Fixed
In Strict Mode, many operations that silently failed are now transformed into errors that throw an exception.
- Error in Read-Only Property Assignment: Assigning a value to a read-only property (e.g., using Object.freeze()) silently fails in sloppy mode but throws a TypeError in Strict Mode.
- Error in Getter-Only Property Assignment: Similarly, assigning to a getter-only property (a property without a setter) throws an error in Strict Mode instead of silently failing.
- Errors for Addition on Non-Extensible Objects: Adding a property on objects marked as non-extensible (Object.preventExtensions()) will throw an error in Strict Mode.
- Delete Statements Not Allowed on Variables: The deletion of variables, functions, and function arguments (delete x;) is now a syntax error in Strict Mode.
- Faster Bug Discovery: All these changes allow bugs to be discovered the instant they are executed at the point of error instead of confusing things somewhere else.
Example of Non-Extensible Object Error:"use strict";
const car = Object.freeze({ brand: "Toyota" });
car.brand = "Honda"; // TypeError: Cannot assign to read only property 'brand'
"use strict";
let obj = {};
Object.preventExtensions(obj);obj.newProp = "test"; // TypeError: Cannot add property newProp, object is not extensible
Duplicate Names Banned
Strict Mode prevents duplicate parameters and duplicate object property names, which might cause confusion to the interpreter.
- Old Sloppy Approach: Under the old approach, a function such as function add(a, a, b) would have been valid, and the second "a" would overwrite the first.
- SyntaxError under Strict Mode: If the same were written in Strict Mode, it would generate a SyntaxError immediately, and the function would not even get declared.
- Old Rule on Duplicate Object Keys: Old Strict Mode even complained about duplicate keys in object literals, although recent JavaScript supports this behavior in both modes.
- Helps Avoid Typo Mistakes: Helps avoid typo mistakes where you accidentally write a new parameter name but repeat an existing one.
- Forces You to Define Clean Parameters: Forces you to define clear parameters, and this is particularly helpful for beginners learning about function parameters.
Example of Correct, i.e., Unique Parameters:"use strict";
function multiply(x, x, y) {
// SyntaxError: Duplicate parameter name not allowed in this context
return x * y;
}
// Correct version
"use strict";function multiply(x, z, y) {
return x * z * y;
}console.log(multiply(2, 3, 4)); // 24
The 'this' Keyword Changes
"Strict Mode" changes how the this value is treated within regular functions if they do not have an object attached to them when they are called.
- Global Object in Sloppy Mode: When a function is called in sloppy mode, without having any object attached to it, this value will be automatically set to the global object (window or global).
- Undefined in Strict Mode: In Strict Mode, however, this value is undefined in this case, rather than being the global object.
- Eliminates Bug Category: It eliminates a bug category wherein the this value accidentally modifies the global objects while the developer is unaware of this fact.
- Throws Clear TypeError: Whenever the developer tries to access the property of the this value, which is undefined, JavaScript gives a clear TypeError.
- Requires Explicit Binding: In order to get the object, explicit binding of objects is needed for a function.
Example of 'this' In Sloppy Mode:"use strict";
function showThis() {
console.log(this);
}showThis(); // undefined (in strict mode)
// Compare with sloppy mode
function showThisSloppy() {
console.log(this);
}showThisSloppy(); // Window object (in browsers) or global object (in Node.js)
Reserved Words Protected
In Strict Mode, specific words are reserved for future JavaScript versions so that you cannot use them for naming variables.
- Future Keywords: Implementing, interface, package, private, protected, public, static, let, and yield are some of the future keywords reserved in Strict Mode.
- Throws SyntaxError: If you try to use any of the above reserved words as a variable name in Strict Mode, you will get a SyntaxError.
- Can Be Used in Sloppy Mode: Some of the above words can even be used in sloppy mode, but it is not recommended.
- Safe From Future Problems: This is done to protect your program from future problems since these words are likely to become programming keywords in the future.
- General Guideline For Beginners: It is a good guideline for beginners in that if a word resembles a programming keyword, then don’t use it as a variable name.
Example of Correct Form, i.e, Safe Variable Name:"use strict";
let interface = "test"; // SyntaxError: Unexpected strict mode reserved word
// Correct: use a different variable name
"use strict";let userInterface = "test";
console.log(userInterface); // "test"
Octal Literals Restricted
The old way of using octal numbers has been prohibited by Strict Mode because it leads to confusion and errors.
- Sloppy Mode Octal Number Error: In sloppy mode, numbers such as 013 were silently converted to octal numbers, which meant that the number actually equalled 11.
- Throws SyntaxError in Strict Mode: In Strict Mode, writing an octal number literal like 013 throws a SyntaxError.
- New 0o Prefix Format: Even though modern JavaScript still allows you to use octal numbers, this can be done only through the new format, i.e., 0o13.
- No Chance to Make Mistakes: By prohibiting old octal numbers, beginners are prevented from making unintentional mistakes due to the misleading nature of octal numbers.
- Removing the Historical Trap: This is one of the best examples where the usage of Strict Mode helps in removing historically misleading features.
Example of Correct Form, i.e, Modern Octal Syntax:"use strict";
let num = 013; // SyntaxError: Octal literals are not allowed in strict mode.
// Correct modern way to write octal numbers
"use strict";let num = 0o13; // valid, equals 11 in decimal
console.log(num); // 11
Arguments Object Behavior
Strict Mode alters how the special arguments object interacts with a function's parameters.
- Linked to Sloppy Mode: In sloppy mode, modifying a named parameter also modifies the same value in the arguments object, and conversely.
- In Strict Mode: In strict mode, the arguments object and named parameters are entirely unrelated in the sense that modifying one does not affect the other.
- Improved Predictability: Function behavior becomes much more predictable since the learner doesn't have to be wary of an invisible link.
- arguments.callee Disabled: Accessing the property arguments .callee is disabled in strict mode and leads to a TypeError.
- Encourages Use Of Better Practices: All of these changes encourage programmers to move on to more advanced practices such as the use of rest parameters (...args).
Sloppy Mode Comparison:"use strict";
function demo(a) {
a = 99;
console.log(arguments[0]); // 10 (unaffected by the reassignment above)
}demo(10);
// Sloppy mode comparison (no "use strict")
function demoSloppy(a) {
a = 99;
console.log(arguments[0]); // 99 (linked to the parameter in sloppy mode)
}demoSloppy(10);
Where It Applies Automatically
Some JavaScript constructs will always be in strict mode, regardless of whether you add the directive.
- Classes Are Always Strict: Any code that goes inside an ES6 class (that uses the class keyword) will always be in strict mode.
- Modules Are Always Strict: Code in an ES6 module (file that uses import/export syntax) is automatically strict too.
- Scripts Are Not Always: Standard <script> tags, Node.js CommonJS files, and regular functions do not have the directive added automatically.
- Safer in Classes: Since classes/modules are always strict, this in a class method will follow strict rules; hence, no global object problem.
- Language Evolving: The gradual move to being "strict by default" in the new constructs is evidence of JavaScript evolving in the right direction.
Module Example (Auto-Strict):// This class is automatically strict, no directive needed
class Calculator {
add(a, b) {
// 'this' behaves in strict mode here automatically
return a + b;
}
}const calc = new Calculator();
console.log(calc.add(5, 7)); // 12
// This ES6 module file is automatically strict
export function double(n) {
return n * 2;
}
Conclusion
Even though Strict Mode might seem like only one line, namely “use strict”; it tightens up some common mistakes in JavaScript programming.
Strict Mode stops any errors related to using a variable accidentally as a global one, assignments that make no sense, duplicate arguments, and improper use of the this operator.
It teaches the novice programmer how to write cleaner and safer code, as well as helps detect bugs.
Modern JavaScript language with such features as classes and modules uses Strict Mode by default.
Thus, there is no good reason not to use it when it comes to modern projects.
FAQs
1. Does using Strict Mode speed up the execution of my JavaScript code?
It does in most cases, but the increase in performance is negligible. The reason is that since Strict Mode gets rid of all the ambiguity (such as the arguments object), JavaScript engines are able to execute the strict mode code more efficiently than sloppy-mode code.
2. Can I use both strict and non-strict code in the same file?
Yes, but only on the level of functions. If you put "use strict"; in some specific function, then this particular function will run in Strict Mode, while all the rest of the functions in the file will run in sloppy mode unless the directive is put right at the beginning of the file.
3. Am I required to explicitly write "use strict" inside the class or module?
No. Strict mode is used automatically by default for all ES6 classes and ES6 modules.
4. Can enabling Strict Mode break my existing older code?
It can, but that is the purpose of the mode; it reveals hidden bugs that were previously going unnoticed. Things like unintentional global variables or invalid assignments become errors after turning on Strict Mode.
5. Is Strict Mode supported by all browsers and Node.js?
Yes. Introduced in ES5 in 2009, Strict Mode works in all browsers (including Chrome, Firefox, Safari, and Edge) and in all versions of Node.js.
0 Comments