What are the Benefits of Using the use strict Directive in JavaScript ?
Last Updated :
12 Feb, 2024
The "
use strict
"
directive enables strict mode in JavaScript, which provides several benefits:
- Strict mode eliminates some JavaScript silent errors by changing them to throw errors.
- Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
- Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
- It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
- It disables features that are confusing or poorly thought out.
- Strict mode makes it easier to write “secure” JavaScript.
Example: Here, the code is in strict mode due to the presence of the "use strict"
directive at the beginning. When the variable x
is assigned a value without being declared first, a ReferenceError
is thrown, indicating that x
is not defined. Strict mode helps catch such errors at runtime, making the code more robust.
Output:
// Throws a ReferenceError: x is not defined
Share your thoughts in the comments
Please Login to comment...