Javascript Strict Mode

Being Javascript a scripting language, sometimes code displays the correct result even it has some errors. To overcome this problem we can use the JavaScript strict mode.

The JavaScript provides “use strict”; expression to enable the strict mode. If there is any silent error or mistake in the code, it throws an error.

This expression can only be placed as the first statement in a script or in a function. Now take a example without using “use strict”.

Input:-
 <script>  
	    x = 20;  
     document.write(x);
</script>

Output:-

Here, I did not provide any type, still I am getting the value of x. Now we will try with using “use strict”.

Input:-
 <script>  
	    "use strict";
	    x = 20;  
     document.write(x);
</script>

Output:-

Now we will try with duplicate names with use of “use strict”.

Input:-
 <script>  
	    document.write(sum(20,30));  
     function sum(a,a){  
        "use strict";  
        return a*a;  
     }.write(x);
</script>

Output:-

Below are some points which we should keep in mind while using this strict mode within our code:-

  • Using a variable, without declaring it, is not allowed.
    • Using an object, without declaring it, is not allowed.
    • Reserved word cannot be used as variables.
    • Writing to a get-only property is not allowed.
    • Deleting a variable (or object) is not allowed.
    • Deleting a function is not allowed.
    • Duplicating a parameter name is not allowed.
    • Octal numeric literals are not allowed.
    • Octal escape characters are not allowed.