Javascript-Strict mode
JavaScript is a loosely typed (dynamic) scripting language. we have worked with server-side languages like Java / C# and you must be familiar with the strictness of the language.
Example: In the compiler to give an error you can use a variable before defining it.
JavaScript allows strictness of code using “use strict” mode with ECMAScript 5 or later. Write “use strict” mode at the top of JavaScript code or in a function.
Example: strict mode
<!DOCTYPE html>
<html>
<body>
<h1>Demo: strict mode</h1>
<p id="errorMessage"></p>
<script>
"use strict";
try
{
var x = 1; // valid in strict mode
y = 1; // error
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
</script>
</body>
</html>
OUTPUT:
Demo: strict mode
ReferenceError: y is not defined
Javascript strict mode does not allow the following things:
- Use of undefined variables
- Duplicate properties of an object
- Duplicate parameters of the function
- Assign values to read-only properties
- Modifying arguments object
- Octal numeric literals
- with statement
- eval function to create a variable
Duplicate property names of an object:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: strict mode</h1>
<p id="errorMessage"></p>
<script>
"use strict";
try
{
var myObj = { myProp: 100, myProp:"test strict mode" }; // error
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
</script>
</body>
</html>
OUTPUT:
Demo: strict mode
Duplicate parameters:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: strict mode</h1>
<p id="errorMessage"></p>
<script>
"use strict";
try
{
function Sum(val, val){ return val + val }; // error
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
</script>
</body>
</html>
OUTPUT:
Demo: strict mode
