Basics

JS Strict Mode

JavaScript Strict Mode

JavaScript strict mode enforces stricter rules, limiting errors.

What is JavaScript Strict Mode?

JavaScript strict mode is a feature introduced in ECMAScript 5 that allows you to place a program or a function in a "strict" operating context. This strict context prevents certain actions and throws more exceptions, helping developers write cleaner code and avoid common pitfalls.

How to Enable Strict Mode

To enable strict mode in JavaScript, you simply need to add the string "use strict"; at the beginning of a script or a function. When placed at the top of a script, it applies to the entire script. When placed inside a function, it applies only to that function.

Benefits of Using Strict Mode

Strict mode offers several benefits, including:

  • Error Prevention: It helps in catching common coding bloopers, preventing the use of undeclared variables, for example.
  • Security Improvements: Certain actions that make the code unsafe or unpredictable are disallowed.
  • Enhanced Performance: Some JavaScript engines can optimize code better when strict mode is used.

Common Errors Caught by Strict Mode

When using strict mode, JavaScript will throw errors in situations where it would otherwise fail silently. Some common errors caught include:

  • Assigning values to undeclared variables.
  • Deleting variables or objects that are not deletable.
  • Using reserved keywords as variable names.

Limitations of Strict Mode

While strict mode is beneficial, it has limitations and certain context-specific behaviors. For example, it does not apply to eval() and with statements within its scope. Also, strict mode is not applied to dynamically created functions unless explicitly specified.

Previous
RegExp