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.
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.
-
-
- 'use strict';
- var counter = 0;
- .....
- .....
-
- .....
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.
- function myfunction() {
- 'use strict';
- ...
-
- ...
- }
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.
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!