Strict Mode

Excerpt from JavaScript: Novice to Ninja

Strict Mode

ECMAScript 5 includes a strict mode that produces more exceptions than warnings and prohibits the use of some deprecated features. For example, trying to assign a value to a variable that is undeclared will result in an exception:

e = 2.718;
<< ReferenceError: e is not defined

Increasing the chance of errors might seem like a bad idea at first, but it’s much better to spot errors earlier on, rather than have them cause problems later. Writing code in strict mode can also help to improve its clarity and speed, since it follows conventions and will throw exceptions if any sloppy code practices are used.

Not using strict mode is often referred to as “sloppy mode” as it is forgiving of sloppy programming practices. Strict mode encourages a better quality of JavaScript to be written that befits a ninja programmer, so its use is recommended.

Strict mode simply requires the following string to be added to the first line of a JavaScript file:

"use strict";

This will be picked up by any JavaScript engine that uses strict mode. If the engine does not support strict mode, this string will simply be ignored.

You can even use strict mode on a per-function basis by adding the line inside a function. Strict mode will then only be applied to anything inside that function:

function strictly(){
  "use strict";
}

In fact, the recommended way to invoke strict mode is to place all of your code into a self-invoking function (covered in more detail in Chapter 12), like so:

(function() {
  "use strict";

  // All your code would go inside this function

   }());

Placing "use strict" at the beginning of a file will enforce strict mode on all the JavaScript in the file, and if you are using anybody else’s code, there’s no guarantee that they’ve coded in strict mode. This technique will ensure that only your code is forced to use strict mode.

Linting Tools

Linting tools such as JS Lint, JS Hint, and ES Lint can be used to test the quality of JavaScript code, beyond simply using strict mode. They are designed to highlight any sloppy programming practices or syntax errors, and will complain if certain style conventions are not followed, such as how code is indented. They can be very unforgiving and use some opinionated coding conventions, such as not using the ++ and -- increment operators (in the case of JS Lint).

Passing a lint test is no guarantee that your code is correct, but it will mean it will be more consistent and less likely to have problems. Some of the errors and warnings that these tools produce can be difficult to understand, but the brilliant JS Lint Error Explanations site is a helpful resource when trying to interpret them.

Get instant access to all books and courses.

Free Trial