What is Strict mode in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Strict mode

Strict mode was introduced by ECMAScript 5 to javascript. Using strict mode javascript silent errors can be easily detected as they would throw an error. This makes javascript debugging much easy and helps developers to avoid unnecessary mistakes.

Since strict mode throws an exception when an undeclared variable is encountered, memory leaks will be greatly reduced. The strict mode can be enabled by using "use strict" in front of the code where strict mode is required. 

In the following example two variables were used, one is outside the function and other one is inside the function. The variable that is used outside the function is not declared, whereas the variable that is declared inside a function is declared using var keyword. Using strict mode inside the function don't throw any error because variable is declared at the same time value in the variable outside the function will be displayed because there is no strict mode used. 

Example-1

Live Demo

<html>
<body>
<script>
   myString1 = "non-strict mode will allow undeclared variables"
   document.write(myString1);
   document.write("</br>");
   function myFun(){
      "use strict"
      var myString2 = "Strict mode will allow declared variables"
      document.write(myString2);
   }
   myFun();
</script>
</body>
</html>

Output
non-strict mode will allow undeclared variables
Strict mode will allow declared variables

In the following example, variable is not declared inside the function and strict mode is applied. So value inside that variable won't be executed and throws error. We can found the error in browser console.

Example-2

Live Demo

<html>
<body>
<script>
   myString1 = "non-strict mode will allow undeclared variables"
   document.write(myString1);
   document.write("</br>");
   function myFun(){
      "use strict"
      myString2 = "Strict mode will allow declared variables"
      document.write(myString2);
   }
   myFun();
</script>
</body>
</html>

Output
non-strict mode will allow undeclared variables

raja
Published on 06-Jun-2019 17:31:46
Advertisements