Strict mode in JavaScript

Strict mode in JavaScript

The JavaScript has a property of hoisting in which you can use a variable without its deceleration but the “use strict” is opposite to it. The “use strict” is the strict mode of JavaScript which force user to declare its variables before their use.

The string or expression “use strict” define the code must be executed in strict mode.

The old version of javascript does not support that property this is not a statement, but it’s a literal expression.

While coding JavaScript in strict mode the undeclared variable cause error.

Example:

If we execute the above code without strict mode, it will work fine. It is because of hoisting which takes all variable declarations to the top of the script, but if we use “use strict” expression at the start of the script, this will cause an error that the variable is undefined.

If we use the “use strict” expression at the top or beginning of the script. It has a global scope and will affect all the rest of code, but if we define it in some function or class, its scope is then limited, it only affects the specific function or class.

The above code causes an error because the “use strict” has global scope.

In the above code the name1 has no error but the name2 which is inside the function cause error, that the variable is undefined because this time the use strict has the local scope and just affects the code inside the function.

Advantages of Strict Mode:

The strict mode provides you a way to execute your code in safe mode or secure mode.

It forces you to write the syntax right. It will enhance programming concepts that the variable must be declared before its use, so the strict mode force programmer to code right and as the JavaScript hoisting provide you the miss behave. If a variable is not declared, hoisting makes it global and take its declaration automatically to the top and the strict mode do not allow the developer to declare the variable after its use.

 

The “use strict” not only affects the variables but the JavaScript object also.

It doesn’t allow an object creation without its declaration.

Other functionalities:

The “use strict” mode not only affects the variable and object declaration but also effect the following programming executions

  • Deleting a variable and or an object is not allowed.
  • Deleting a function is not allowed.
  • Duplicating a parameter name of a function is not allowed.
  • Octal numeric literals are not allowed.
  • Escape sequence characters are not allowed.
  • Writing to a read-only property is not allowed.
  • Writing to a get-only property is not allowed.
  • Deleting an undeletable property is not allowed.
  • The string “eval” cannot be used as a variable.
  • The string “arguments” cannot be used as a variable.
  • The with statement is not allowed.

All the future reserve keywords of JavaScript are not allowed in “use strict” mode.