JavaScript Strict Mode (With Examples)

JavaScript is a loosely typed (dynamic) scripting language. If you have worked with server side languages like Java or C#, you must be familiar with the strictness of the language. For example, you expect the compiler to give an error if you have used a variable before defining it.

JavaScript allows strictness of code using "use strict" with ECMAScript 5 or later. Write "use strict" at the top of JavaScript code or in a function.

Example: strict mode
"use strict";

var x = 1; // valid in strict mode
y = 1; // invalid in strict mode

The strict mode in JavaScript does not allow following things:

  1. Use of undefined variables
  2. Use of reserved keywords as variable or function name
  3. Duplicate properties of an object
  4. Duplicate parameters of function
  5. Assign values to read-only properties
  6. Modifying arguments object
  7. Octal numeric literals
  8. with statement
  9. eval function to create a variable

Let look at an example of each of the above.

Use of undefined variables:

Example: strict mode
"use strict";

x = 1; // error

Use of reserved keyword as name:

Example: strict mode
"use strict";

var for = 1; // error
var if = 1; // error

Duplicate property names of an object:

Example: strict mode
"use strict";

var myObj = { myProp: 100, myProp:"test strict mode" }; // error

Duplicate parameters:

Example: strict mode
"use strict";

function Sum(val, val){return val + val }; // error

Assign values to read-only property:

Example: strict mode
"use strict";

var arr = [1 ,2 ,3 ,4, 5];
arr.length = 10; // error

Modify arguments object:

Example: strict mode
"use strict";

function Sum(val1, val2){
    arguments = 100; // error
}

Octal literals:

Example: strict mode
"use strict";

var oct = 030; // error

with statement:

Example: strict mode
"use strict";

with (Math){
    x = abs(200.234, 2); // error
};

Eval function to create a variable:

Example: strict mode
"use strict";

eval("var x = 1");// error

Strict mode can be applied to function level in order to implement strictness only in that particular function.

Example: strict mode

x = 1; //valid

function sum(val1, val2){
    "use strict";

     result = val1 + val2; //error

    return result;
}