ariya.io About Talks Articles

Strict Mode Checks with Esprima

2 min read

Strict mode (see Annex C in ECMAScript 5 specification) is known as a mechanism to use the a restricted variant of JavaScript. Some developers don’t really like it, however my personal experiences demonstrates a lot of good advantages (including catching the unintentional globals) when leveraging this mode.

One of the latest development in Esprima is allowing the parser to understand strict mode (see issue 160). This means, some restrictions of this mode which can be caught at the parsing time will be reported to you. For example, the following snippet:

'use strict';
block = {
  color: 'blue',
  height: 20,
  width: 10,
  color: 'red'
};

will provoke this error:

Error: Line 6: Duplicate data property in object literal not allowed in strict mode

because two properties can’t have the same name (color in the above example) under strict mode. While this seems like a glaring error, in some cases such as a mistake is not necessary easy to spot if the object literal is huge. This is a typical situation when you use various frameworks to implement an object using class-like construct.

If you use JSLint (or its fork JSHint) to lint the above snippet, it will happily report about the duplication. However, this happens even if you don’t specify strict mode (which makes sense, they are checking for code quality after all). Meanwhile, UglifyJS parser won’t complain at all.

Strict mode support for Esprima is still in the development branch. Eventually it would be rolled out in the official web site but meanwhile you can always check the bleeding-edge version and play with it. In one way or another, hopefully this will help you improving the quality of your code!

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook