Open In App

What is Strict Mode and how to enable it in JavaScript ?

Last Updated : 08 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The strict mode of JavaScript, introduced in ECMAScript 5, is a mechanism to opt into a restricted version of JavaScript.” Strict mode modifies the regular JavaScript semantics in the following ways: Some JavaScript silent errors are eliminated by converting them to throw errors.

How to enable strict mode in JavaScript:

Use “use strict” in front of the code where strict mode is necessary to enable strict mode. The strict mode can be enabled by simply 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 error catching becomes easier.

 

Advantages of using strict mode:

  • The strict mode eliminates silent errors by changing them into thrown errors. so, it makes debugging easier
  • When the delete operator is used where it is invalid strict mode throws errors.
  • When the variables are used without being declared or we call them “accidental globals”, strict mode throws an error.
  • It doesn’t allow duplicate property names or parameter values.
  • .When we do not use strict mode and our “this” operator points reference to null or undefined values it doesn’t give an error but enabling the strict mode raises an error.
  • Code written in strict mode can sometimes be made to execute quicker than code written in a non-strict manner.

The strict mode doesn’t allow the following instructions:

  • We cannot directly use variables without declaring the variable.
  • Parameters/arguments duplicates are not allowed.
  • Deletion function not allowed.
  • The words ‘eval’ and ‘arguments’ cannot be used as a variable.
  • The ‘with’ statement is not allowed.
  • Deleting a property that is undeletable.
  • Writing to a read-only property.

Examples:

Demonstration without using the strict mode:  In the below example we are assigning a variable without declaring it and then printing it.

Javascript




a = 1;
console.log(a);


Output:

 

Demonstration with using the strict mode: In the below example we are assigning a variable without declaring it and then printing it. we enable strict mode at the top of the code. The error message is displayed as we use strict mode.

Javascript




"use strict";
a = 1;
console.log(a);


Output: 

Demonstration an example with or without using the strict mode: In the below example one part of the javascript code is running under strict mode and the other is running in non-strict mode.

Javascript




// This will not cause an error
a = 10; .
console.log(a);
withUsingStrict();
  
function withUsingStrict() {
  "use strict";
  b = 20; // This will cause an error
  console.log(b);
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads