How to enable strict mode in JavaScript, and what are its effects on code behavior?
How to enable strict mode in JavaScript, and what are its effects on code behavior?
242
08-Oct-2023
Updated on 09-Oct-2023
Aryan Kumar
09-Oct-2023To enable strict mode in JavaScript, you simply include the following line of code at the beginning of your script or function:
Here's how to enable strict mode and understand its effects on code behavior:
Script-Wide Strict Mode:
To enable strict mode for an entire JavaScript file, place "use strict"; at the very beginning of the file before any other code. For example:
Function-Wide Strict Mode:
You can enable strict mode for a specific function by placing "use strict"; at the beginning of that function. This allows you to apply strict mode selectively to only certain parts of your code. For example:
Module-Level Strict Mode (ES6):
In ECMAScript 6 (ES6) modules, strict mode is enabled by default for the entire module, so you don't need to explicitly add "use strict";. For example:
Now, let's explore the effects of enabling strict mode on code behavior:
Non-Strict Mode Behavior: In non-strict mode, you can assign values to undeclared variables, which results in the creation of a global variable.
Strict Mode Behavior: In strict mode, assigning a value to an undeclared variable is not allowed, and it throws a ReferenceError.
Non-Strict Mode Behavior: In non-strict mode, octal literals (e.g., numbers with leading zeros like 0123) are allowed.
Strict Mode Behavior: In strict mode, octal literals are not allowed, and using them results in a syntax error.
Non-Strict Mode Behavior: In non-strict mode, it's possible to define functions with duplicate parameter names, with the last parameter name taking precedence.
Strict Mode Behavior: In strict mode, declaring a function with duplicate parameter names results in a syntax error.
Non-Strict Mode Behavior: In non-strict mode, when this is referenced in the global scope (outside of any function), it refers to the global object (e.g., window in browsers).
Strict Mode Behavior: In strict mode, when this is referenced in the global scope, it is undefined. This behavior helps prevent accidental modification of the global object.
Non-Strict Mode Behavior: In non-strict mode, you can reassign values to read-only global objects like NaN, Infinity, and undefined.
Strict Mode Behavior: In strict mode, these global objects become read-only, and attempting to reassign them results in a TypeError.
Enabling strict mode is a best practice in modern JavaScript development because it helps catch common coding mistakes, promotes better coding practices, and makes JavaScript more predictable and robust. It encourages writing cleaner and more maintainable code by reducing the risk of bugs and unintended behavior.