Site icon i2tutorials

Javascript-Strict mode

Javascript-Strict mode

 

JavaScript is a loosely typed (dynamic) scripting language. we have worked with server-side languages like Java / C# and you must be familiar with the strictness of the language.

Example: In the compiler to give an error you can use a variable before defining it.

JavaScript allows strictness of code using “use strict” mode with ECMAScript 5 or later. Write “use strict” mode at the top of JavaScript code or in a function.

 

Example: strict mode

 

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: strict mode</h1>

       <p id="errorMessage"></p>

       <script>
              "use strict";
              try
              {
                     var x = 1; // valid in strict mode
                     y = 1; // error
              }
              catch(ex)
              {
                     document.getElementById("errorMessage").innerHTML = ex;
              }

  </script>
</body>
</html>

 

OUTPUT:

 

Demo: strict mode

ReferenceError: y is not defined

 

Javascript strict mode does not allow the following things:

 

 

Duplicate property names of an object:

 

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: strict mode</h1>
           
       <p id="errorMessage"></p>

       <script>
              "use strict";
              try
              {
                     var myObj = { myProp: 100, myProp:"test strict mode" }; // error
              }
              catch(ex)
              {
                     document.getElementById("errorMessage").innerHTML = ex;
              }

  </script>
</body>
</html>

 

OUTPUT:

 

Demo: strict mode

 

Duplicate parameters:

 

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: strict mode</h1>

       <p id="errorMessage"></p>

       <script>
              "use strict";
              try
              {
                     function Sum(val, val){ return val + val }; // error
              }
              catch(ex)
              {
                     document.getElementById("errorMessage").innerHTML = ex;
              }

  </script>
</body>
</html>

 

OUTPUT:

 

Demo: strict mode

 

Exit mobile version