Use Of 'Use Script' In JavaScript And Its Benefits

Introduction 

 
Let's understand what exactly are the uses and benefits of the "use strict" statement in JavaScript.
 

What is this Statement?

 
It is just a normal string that we can put in our JavaScript file at the top or inside of any function as below which enables Strict Mode.
  1. "use strict";  
The above statement tells the browser to use the Strict mode application for Js file or any specific function, just to make your code safe.
 
Let's understand it:
  • It is introduced in ECMAScript 5 and allows us to place it in JavaScript file or in a function to make them follow some "strict" rules during execution.
  • It helps us to prevents some unnecessary action to happen and helps us to throws more exceptions in detail so that we could have more clear and safe script codes.
So how do we use this string or statement? 
 
Insert this text 'use strict'; on top of your script. So here, everything in the file mysamplejsfile.js will be executed in strict mode.
  1. // File Name: mysamplejsfile.js  
  2.   
  3. 'use strict';  
  4. var counter = 0;  
  5. .....  
  6. .....  
  7. // other code  
  8. .....  
Insert this 'use strict'; text on the start of your function body, as shown below. It means that everything in the scope of this function will be executed in strict mode.
  1. function myfunction() {  
  2.     'use strict';  
  3.     ...  
  4.     // other code  
  5.     ...  
  6. }  
Note
In the above code, everything will be non-strict except for the function we mark 'use strict' inside the function. 
 
Example of Exception
 
If you try to assign some value to an undefined variable, it will throw error/exception. Previously it was working.
  1. code = 'some data';  
So the above code will throw an exception, as the 'code' variable is not declared and directly used.
 
I would definitely advise all developers to start using strict mode in their JavaScript files. There are now enough browsers supporting it and it will help save us from errors in the code that we may never have thought about. 
 
Below is the supported list of browsers.
 
https://caniuse.com/#feat=use-strict 
 
I hope this blog was helpful to you!