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.
"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:
- Use of undefined variables
- Use of reserved keywords as variable or function name
- Duplicate properties of an object
- Duplicate parameters of function
- Assign values to read-only properties
- Modifying arguments object
- Octal numeric literals
- with statement
- eval function to create a variable
Let look at an example of each of the above.
Use of undefined variables:
"use strict";
x = 1; // error
</code></pre>
<div className="card-footer example-footer"></div></div>
</div>
<p>
Use of reserved keyword as name:
</p> <div className="card code-panel">
<div className="card-header example-title">Example: strict mode</div>
<div className="panel-body"><pre className="csharpcode"><code>"use strict";
var for = 1; // error
var if = 1; // error
Duplicate property names of an object:
"use strict";
var myObj = { myProp: 100, myProp:"test strict mode" }; // error
Duplicate parameters:
"use strict";
function Sum(val, val){return val + val }; // error
Assign values to read-only property:
"use strict";
var arr = [1 ,2 ,3 ,4, 5];
arr.length = 10; // error
Modify arguments object:
"use strict";
function Sum(val1, val2){
arguments = 100; // error
}
Octal literals:
"use strict";
var oct = 030; // error
with statement:
"use strict";
with (Math){
x = abs(200.234, 2); // error
};
Eval function to create a variable:
"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.
x = 1; //valid
function sum(val1, val2){
"use strict";
result = val1 + val2; //error
return result;
}