JavaScript Strict Mode
Join the DZone community and get the full member experience.
Join For Freethe 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…
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)
Published at DZone with permission of Angus Croll. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
RBAC With API Gateway and Open Policy Agent (OPA)
-
Scaling Site Reliability Engineering (SRE) Teams the Right Way
-
How To Use Pandas and Matplotlib To Perform EDA In Python
-
Database Integration Tests With Spring Boot and Testcontainers
Comments