BStrict Mode

ECMAScript 5 was the first to introduce the concept of strict mode. Strict mode allows you to opt-in to stricter checking for JavaScript error conditions either globally or locally within a single function. The advantage of strict mode is that you'll be informed of errors earlier, so some of the ECMAScript quirks that cause programming errors will be caught immediately.

The rules of strict mode are important to understand, as future versions of ECMAScript will mandate the increasingly pervasive use of strict mode. Strict mode is supported in all major browsers.

OPTING-IN

To opt-in to strict mode, use the strict mode pragma, which is simply a string that isn't assigned to any variable:

"use strict";

Using this syntax, which is valid even in ECMAScript 3, allows seamless fallback for JavaScript engines that don't support strict mode. The engines that support strict mode will enable it, while engines that don't will simply ignore the pragma as an unassigned string literal.

When the pragma is applied globally, outside of a function, strict mode is enabled for the entire script. That means adding the pragma to a single script that is concatenated with other scripts into a single file puts all JavaScript in the file into strict mode.

You can also turn on strict mode within a function only, such as:

function doSomething() {
 "use strict";
 // other processing
}

If you don't have complete control over all of the scripts on a page, then it's advisable to enable strict ...

Get Professional JavaScript for Web Developers, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.