📌 Need:
Strict Mode is a feature introduced in ECMAScript 5 that allows you to enforce a stricter parsing and error handling in your JavaScript code. It helps in catching common coding errors and improving the security and performance of JavaScript code.
Why Use Strict Mode?
- Error Detection: It makes it easier to write secure JavaScript code by throwing errors for bad syntax and unsafe operations that are otherwise silently ignored in non-strict mode.
- Prevents Global Variables: It prevents the accidental creation of global variables, which helps avoid potential bugs and conflicts.
- Enforces Safe Coding Practices: It enforces stricter parsing and error handling, such as throwing errors for assignment to non-writable properties, using undefined variables, or other unsafe operations.
- Improves Performance: Some JavaScript engines can optimize code more aggressively when it is running in strict mode.
How to Enable Strict Mode
Strict mode is declared by adding "use strict";
at the beginning of a script or a function.
Global Strict Mode:
"use strict"; // This code is in strict mode x = 3.14; // Error: x is not declared
Key Differences with Non-Strict Mode
- Variable Declarations: In strict mode, all variables must be declared with
var
,let
, orconst
. Undeclared variables will cause an error. - Assignment Errors: Strict mode throws an error for assignments to read-only properties, non-existent properties, or the
this
keyword used in an inappropriate context. - Reserved Keywords: Certain keywords are reserved for future use and cannot be used as identifiers in strict mode.
Additional Information
- Strict Mode in ES6: In ES6 and later, strict mode can also be applied to modules and classes automatically, without the need for
"use strict";
. - Limitations: Strict mode does not affect existing code and is only enforced in the blocks where it is explicitly declared.