JavaScript Strict Mode is a crucial aspect of writing efficient and secure code. It was introduced in ECMAScript 5 (ES5) to address some of the issues of the language's "sloppy mode" and enforces stricter rules for JavaScript code, making it more secure and less prone to errors.
All variables must be declared
One of the main features of Strict Mode is that it prevents the use of undeclared variables. This means that any variable that has not been explicitly declared with the var
, let
, or const
keywords will result in an error. This helps catch potential errors early on and encourages developers to write more organized and maintainable code.
Disabled Features
Strict Mode also disables certain features that are considered to be problematic, such as with
statements and implicit global variables. This helps prevent common mistakes that can lead to security vulnerabilities and other issues.
Enable globally
'use strict';
x = 42;
Error - x is not declared
NB: The 'use strict'
statement will be ignored by old browsers that don't support strict mode.
Limited strict
Strict mode can be enabled in a local context - eg: inside a function:
x = 42;
No Error (strict mode not on here)
function myFunction() {
'use strict';
y = 42;
}
Error - y is not declared
The use of JavaScript Strict Mode is highly recommended for any JavaScript project. It can help catch errors early on, prevent common mistakes, and make code more secure and maintainable.
Top comments (0)