JavaScript – Strict mode

Strict mode is new feature in ECMA Script 5. This mode allows you to run program, piece of program (context) in strict mode.

This mode will help your code by throwing error if your program violets standard.

Let’s see example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Use Strict mode</title>
</head>
<body onload="loadDoc()">
<div id="content1"></div>
<div id="content2"></div>
<script type="text/javascript">
var ele1 = document.getElementById("content1");
foo1 = "Hello";
ele1.innerHTML = "" + foo1;
function loadDoc() {
"use strict";
var ele2 = document.getElementById("content2");
foo2 = "Hello from page load";
ele2.innerHTML = "" + foo2;
}
</script>
</body>
</html>

In above example we have used foo1 and foo2 variables without declarations.
Here we put “use strict”; statement in loadDoc() function then it will throw error like below(tested in chrome). Uncaught
ReferenceError: foo2 is not defined Just add declaration of foo2 in loadDoc() function and browser will not throw any error.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Use Strict mode</title>
</head>
<body onload="loadDoc()">
<div id="content1"> </div>
<div id="content2"> </div>
<script type="text/javascript">
var ele1 = document.getElementById("content1");
foo1 = "Hello";
ele1.innerHTML = "" + foo1;
function loadDoc() {
"use strict";
var ele2 = document.getElementById("content2");
var foo2 = "Hello from page load";
ele2.innerHTML = "" + foo2;
}
</script>
</body>
</html>

Output is:

JavaScript Strict Mode

If you put “use strict” at top of file, then it will enable strict mode in entire file. It keeps your code safe and standard.

Note: You will not see any error in IE9 or below browser. IE 10 will support strict mode.

http://msdn.microsoft.com/en-us/library/ie/hh673540(v=vs.85).aspx