What is Strict Mode in JavaScript and How to Enable It?



The Strict mode was introduced in ECMAScript 5 in JavaScript. It is a mechanism to opt into a restricted version of JavaScript. Strict mode modifies the regular JavaScript semantics. Some JavaScript silent errors are eliminated by converting them into throwing errors in Strict mode.

How to enable strict mode in JavaScript

We can use the “use strict” at the beginning of the code to enable the strict mode. The strict mode can be enabled by stating it at the top of your script or in the required function. When a JavaScript engine encounters this directive, it begins to parse the code in a specific mode where the error catching becomes easier.

Advantages of using strict mode

  • Strict mode eliminates all the silent errors by changing to throw errors which makes debugging easier.

  • It throws an invalid strict mode error on trying to use the delete operator.

  • It throws an “Uncaught ReferenceError” error when the variables are used without being declared.

  • It does not allow duplicate property names or parameter values.

  • Code written in strict mode executes faster as compared to that written in non-strict mode.

Strict Mode doesn’t allow the following instructions

  • Variables cannot be directly used without declaration.

  • Parameters/arguments duplicates are not allowed.

  • Deletion function is not allowed.

  • We cannot use ‘eval’ and ‘arguments’ keywords as variables.

  • We cannot perform writing on a read-only property.

Example 1

In the below example, we are using the strict property and then checking how it makes any difference.

# index.html

<html>
<head>
   <title>Strict Mode</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      "use strict";
      a = 1;
      console.log(a);
   </script>
</body>
</html>

Output

Since the variable is not defined it throws the below error in strict mode. Output can be seen in the Console.

Uncaught ReferenceError: a is not defined
   at index.html:13:7

Example 2

In the below example, both variable 'a' and 'b' are not declared. But variable 'b' is in strict mode whereas 'a' is not. Hence it will throw an error for 'b' as it is in strict mode.

# index.html

<html>
<head>
   <title>Strict Mode</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // This will not cause an error
      a = 21;
      console.log("Non-Strict Mode: " + a);
      withUsingStrict();
      function withUsingStrict() {
         "use strict";
         console.log("This will throw error in strict mode.")
         b = 20; // This will cause an error
         console.log(b);
      }
   </script>
</body>
</html>

Output

It will produce the following output in the Console.


Advertisements