JavaScript Strict Mode in IE 10

Strict Mode has been introduced from ECMAScript 5.0, the intent is to encourage developers choose an more standard version of JavaScript. For a long time, JavaScript has been┬ácontroversial for its loose and flexible syntax. Including Strict Mode in ECMAScript 5.0 makes it possible for Javascript’s interpreter to parse lines using Strict Mode syntax, which helps developers locate bugs. Strict Mode is be full-supported by Firefox, opera and other modern browsers except IE(6-9). With the recent release of Internet Explorer 10, it’s confirmed that Strict Mode is formally supported by IE 10.

How to activate Strict Mode?

It’s simple to enable strict mode, just include this statement before your scripts:

"use strict";

This statement is compatible with old browsers that don’t support strict mode. You can place it at the very first line of your scripts to work globally, or only within the function you want to debug. I personally recommend the latter, because letting all your code run in strict mode can causes many problems, and even worse when the script file is big. It’s better to only use strict mode within functions, for example:

function sayHello(){
  "use strict";
  alert("hello!");
  //this runs in strict mode
}

What does Strict Mode do?

Avoiding any accidental undeclared global variables

"use strict";
x = 5; // this undeclared variable will throw an exception

Eliminates this coercion

window.hello= "Hello";
function sayHello() {
alert(this.hello); //error
}

Prevent redefining

var someObject = {
  prop: "test",
  prop: "test2" //error
};

Variable declared in eval() will not be created

function sayHellow(){
  eval("var str='Hellow!';");
  alert(str); //in strict mode, str is undeclared, this will throw an error
};

Furthermore, Strict Mode removes support for with.

Conclusion

I highly recommend you use Strict Mode in your scripts, it not only helps you revealing errors you would never notice, but also gets you in the habit of writing better code, which is always considered a good thing.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>