In JavaScript, Strict Mode is a way to enforce a stricter set of rules on your code, making it easier to catch common coding mistakes and "unsafe" actions. It helps improve performance and security by preventing the use of certain error-prone features.
You enable strict mode by adding the following directive at the beginning of a script or a function:
Without strict mode:
With strict mode:
Without strict mode:
With strict mode:
Without strict mode:
With strict mode:
this
in functions undefined
instead of window
(in non-method calls).Strict mode helps make your code more secure and easier to debug.
You need Strict Mode in JavaScript to improve code quality, prevent common bugs, and enhance security by enforcing stricter parsing and error handling rules. Here’s why strict mode is useful:
Without strict mode, assigning a value to an undeclared variable creates a global variable, which can lead to unexpected behavior and conflicts.
Without strict mode:
With strict mode:
Strict mode prevents the use of future JavaScript reserved words (like public
, static
, implements
) as variable names, which helps ensure compatibility with future language updates.
Example:
Strict mode throws an error when assigning values to non-writable or non-configurable properties.
Example:
In non-strict mode, JavaScript allows functions to have duplicate parameter names, which can lead to confusion and bugs.
Example:
this
undefined
in functionsWithout strict mode, this
defaults to the global object (window
in browsers) when used in a function. In strict mode, this
remains undefined
unless explicitly bound.
Example:
Some JavaScript operations fail silently without strict mode. Strict mode converts these into visible errors, making them easier to debug.
Example:
Strict mode helps write cleaner, more predictable, and less error-prone code.