Use Strict Mode In JavaScript

Introduction

 
In this blog, I am going to discuss about strict mode in JavaScript. We can use strict mode in two way in a JavaScript code, 
  1. On the page level.
  2. On the function level.
On the page level,
  1. <script>  
  2.     "use strict"  
  3.     GetPiValue();  
  4.   
  5.     function GetPiValue() {  
  6.         y = 3.14;  
  7.         console.log(y);  
  8.     }  
  9. </script>  
In the above code, we used "use strict" at top of the page. When we run it, we are getting the following error.
 
 
On the function level,
  1. <script>  
  2.     GetPiValue();  
  3.   
  4.     function GetPiValue() {  
  5.         "use strict"  
  6.         y = 3.14;  
  7.         console.log(y);  
  8.     }  
  9. </script>  
Again, in the above code, we used "use strict" inside the method. When we run it, we are getting the same error. 
 
 
Why we are getting the above error for using "use strict".?
 
We use this mode for better coding and error checking in JavaScript code. If we use strict mode, then we are not allowed to do many things. Below are some operations you cannot perform in strict mode.
  • Assigning value to non-declared variable
  • Assigning value to read only variable
  • Defining duplicate property in a function
  • Cannot define a function inside else-if or for statement
Many other operations will give error for using "use strict". I hope you have understood the purpose of this article . Thanks for reading.