Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Strict Mode

DZone's Guide to

JavaScript Strict Mode

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

The fifth edition of the ECMAScript specification introduced Strict Mode. Strict Mode imposes a layer of constraint on JavaScript – intended to protect you from the more perilous aspects of the language.

While researching this article I wrote 38 tests covering all the Strict Mode rules as defined in the ES5 specification. You can see how your favorite browser shapes up by clicking here.

The code for each test is reproduced at the end of the article as an aid to understanding the specification. You can also run the tests manually by copying and pasting the source into the console. The full source code is on my github repo.

Firefox 4 and IE10 (preview 1) already fully support Strict Mode, and Chrome 12 is nearly there. Strict Mode is here to stay – let’s dive in…

How do I invoke Strict Mode?

Adding “use strict” as the first statement in your JavaScript code will enforce Strict Mode over the entire source…

"use strict";
2 012; //Octal literal throws a SyntaxError in Strict Mode

Alternatively you can restrict Strict Mode enforcement to a given function, by adding a “use strict” statement to the first line of the function body…

012; //No Error (Strict Mode not enforced globally)
2 function foo() {
3 "use strict";
4 x=3; //Strict Mode will throw an error for implicit globals
5 }
6 foo(); //ReferenceError (Strict Mode is enforced for function foo)

Do functions reflect the Strict Mode directives of their outer functions?

Inner functions defined within an outer function that carries the “use strict” directive, will also be subject to Strict Mode…

var wrapper = function(fn) {
02 'use strict';
03 var deleteNonConfigurable = function () {
04 var obj = {};
05 Object.defineProperty(obj, "name", {
06 configurable: false
07 });
08 delete obj.name; //Will throw TypeError in Strict Mode
09 }
10 return deleteNonConfigurable;
11 }
12
13 wrapper()(); //TypeError (Strict Mode enforced)

However it is important to note, Strict Mode is not enforced on non-strict functions that are invoked inside the body of a strict function (either because they were passed as arguments or invoked using call or apply)…

var test = function(fn) {
02 'use strict';
03 fn();
04 }
05
06 var deleteNonConfigurable = function () {
07 var obj = {};
08 Object.defineProperty(obj, "name", {
09 configurable: false
10 });
11 delete obj.name; //will throw TypeError in Strict Mode
12 }
13
14 test(deleteNonConfigurable); //no error (Strict Mode not enforced)


Why can’t I run global Strict Mode in my browser console?

When running code in firebug and other browser consoles, an initial “use strict” (outside a function) has no effect. This is because most console runners wrap all code in an eval call – so your “use strict” is no longer the first statement. A partial workaround is to wrap your code in a self invoking function starting with “use strict” (but even then, I found enforcement of Strict Mode within the console to be pretty flakey – particularly when using webkit developer tools – better to test your code in a web page):

 

(function() {
2 "use strict";
3 var a;
4 var b;
5 function bar() {
6 x = 5; //Strict Mode will throw an error for implicit globals
7 }
8 bar(); //ReferenceError (Strict Mode is enforced)
9 })();

What happens if my browser doesn’t support Strict Mode?

Nothing. The “use strict” directive is simply a string statement that will be ignored by JavaScript engines that don’t support Strict Mode. This allows safe cross-browser use of Strict Mode syntax while ensuring built-in forward compatibility with browsers that might support Strict Mode in the future.

What are the rules of Strict Mode?

The restrictions defined by the Strict Mode specification encompass both load-time and runtime behaviors. Here’s a brief overview (each rule is covered in detail, with an example, in the next section):

Syntax Errors

In many cases, Strict Mode will prevent ambiguous or allegedly misleading code from even loading. Octal literals, duplicate property names, incorrect usage of delete and attempts to do anything dodgy with the eval and arguments keywords will throw a SyntaxError as will any use of the with statement.

The ‘this’ value

In Strict Mode the value of this will not be auto-coerced to an object. This is probably the most interesting part of Strict Mode and the one that is likely to have the most significant impact on developers. Most notably, if the first argument to call or apply is null or undefined, the this value of the invoked function will not be converted to the global object.

Implicit globals

Not many folks will argue against this one. Creation of implicit globals is almost always a mistake. in Strict Mode you’ll get a ReferenceError. That’ll teach you ;-)

arguments.caller and arguments.callee

These useful properties are frowned upon in Strict Mode. Definitely controversial. The lesser used function.arguments and function.caller properties are also banned.

Object property definition violations

Attempting to perform an update on a property when its property definition defines otherwise will throw a TypeError in Strict Mode.

The Tests

Here is the full source code from my Strict Mode tests. Each set of tests is preempted by a comment lifted directly from the ECMAScript specification being tested. This version of the source is set to run in “console mode” – meaning it can be copied and pasted into a developer console and run as is. The same source run in “HTML mode” is used to generate the visual test page that I introduced at the top of the article. That source, with supporting objects is on my github repo. I’m sure to have made a few mistakes – feel free to let me know!

Wrap up

Whether restricting access to the language makes for better developers is questionable – but lets save that debate for another time. In its defense, Strict Mode is a nice compromise between a complete language change (which would have broken backwards-compatibility) and doing nothing (which would have raised the hackles of those who insist that the more egregious parts of the language must be phased out). If nothing else, Strict Mode is meat and drink for those of us obsessed with the nuances of this fascinating language. Enjoy!

Further Reading

ECMA-262 5th Edition: The Strict Mode of ECMAScript

Asen Bozhilov: Strict tester
A thoughtful, thorough set of Strict Mode tests.

Juriy Zaytsev (aka “kangax”): ECMAScript 5 compatibility table — Strict mode support
Another good source, part of a major compatibility reference by kangax (thanks also to kangax for a last minute IM chat about these tests)

 

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}