Understanding Strict Mode in JavaScript

Strict mode is enabled in a JavaScript program by adding a special string constant at the beginning of the program:

"use strict";

Also, you can enable strict mode for a function by placing the string constant at the beginning of the function definition.

function dodge() {
	"use strict";
    // ... function body
}

What Does It Do?

Strict mode, when in an EcmaScript 5(ES5) environment, will disallow error-prone aspects of JavaScript. EcmaScript? I thought we were talking about JavaScript? The international language standard for JavaScript was coined EcmaScript way back in 1997!

Don't jump the gun and think strict mode is going chain you up in a JavaScript basement. Before yelling, "Get off my lawn strict mode!", let's look at some things it can prevent. Assuming you have enabled strict mode then you would get error messages when running the JavaScript code below.

// SyntaxError: Variable name may not
// be eval or arguments in strict mode
function f(x) {
    var arguments = [];
}

// SyntaxError: Function name may not be eval or arguments in strict mode
function eval(){}

Strict mode will prevent accidentally messing with eval or arguments in JavaScript. To see a full list of things Strict mode restricts go here.

Compatibility

If you happen to be in an EcmaScript 3 environment then the string will be parsed but nothing will happen. It's goofy to enable a feature with a string but it was done that way to be backwards compatible. If you are on the latest version of FireFox or Chrome then you have ES5 and strict mode support.

Let's look at ES5 and strict mode compatibility with Internet Explorer:

  • IE 8 supports little to no ES5 features.
  • IE 9 supports most ES5 features but not "strict mode".
  • IE 10+ supports all ES5 features (including strict mode".

Gotchas

The "use strict"; statement has to be the first noncomment at the top of a file or at the top of a function expression. When concatenating JavaScript files to optimize file delivery in your website you may run into some issues:

  1. You want to be able to use strict mode on only a portion of your code.
  2. You want to be able to concatenate your files in any order.

The solution to this problem is to use an immediately invoked function expression.

(function() {
	"use strict";
    function jump() {
    }
})();

References