javascript by default run on non-strict mode, in this mode undeclared variable, function same parameters and so many things are allowed. but in strict mode, javascript strictly follows syntax and parsing rules to avoid runtime errors.

strict mode is a literal expression introduced in ECMAScript 5, To implement strict mode “use strict” in javascript program. Strict mode can be applied on entire script or only in function scope.

In strict mode, javascript executes code faster than non-strict mode.

Syntax

<script>
"use strict";
</script>

“use strict” can be written inside double quote and single quote. without quotes it gives error.

Example

<script>
"use strict";
age = 34; // Reference Error
</script>

Above example, gives ReferenceError: age is not defined. because, strict mode needs variable to be declared first and then use it.

Apply Strict mode for entire program or script

To apply strict mode for the entire script, add “use strict” just after <script> tag, entire program will run on strict mode rules.

<script>
"use strict";
a = 3;  // Reference Error
b = 4;  // Reference Error
c = 0;  // Reference Error
c = a + b;
</script>

Because of strict mode undeclared variable gives Reference error.

Script mode in function scope.

strict mode can be used inside functions as well, it is applied inside the function only, statements inside function should follow strict mode rules.

<script>
 function test(){
   "use strict";
    a = 20; // Reference Error
   document.write("function in strict mode");
 }
 test();
</script>

Script mode for function

<script>
 "use strict";
 function test(){
   document.write("Hello strict mode for function");
 }
 test();
</script>

strict mode applied for test() function only.

Duplicate function parameter in strict mode

<script>
   "use strict";
 function test(x, x){
    a = x; // Reference Error
   document.write("function in strict mode");
 }
 test();
</script>

Same name function parameter should not be used in strict mode, it gives error.

Duplicate properties name are not allowed

<script>
"use strict";
const x = { a: 1, a: 2,a:3 }; 
</script>

What strict mode not allows

  1. Undeclared variables.
  2. Duplicate function parameters.
  3. Undeclared objects.
  4. Modules are by default in strict mode.
  5. Classes are by default in strict mode.
  6. Deleting plain variables are not allowed, only with globalThis.variable name is allowed.
  7. Duplicate property names not allowed.