O'Reilly logo

Professional: JavaScript® for Web Developers, Third Edition by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

B

Strict 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 the next version of ECMAScript will start with a base of strict mode. Strict mode is supported in Internet Explorer 10+, Firefox 4+, Safari 5.1+, and Chrome.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required