The use of, and reasons behind, “use strict”

ECMASCRIPT 5 introduces a new mode of execution called strict mode.

As its name may suggest, when enabled it enforces stricter checks on the executable code to reduce the number of silent errors that is can easily be introduced in JavaScript. Instead of failing silently, the code will throw various types of errors; such as ReferenceError or TypeError. This has the huge benefit of allowing common programming errors to be noticed much more easily (as they throw a dirty great red line in your console), rather than failing silently and you, as a developer, having to spend hours tracking weird and wonderful bugs down to a stupid typo. Additionally, strict mode prevents usage which has been deemed as bad practise over the years; encouraging better and more eloquent code.

The beauty of enabling strict mode is that it is entirely backwards compatible and provides great flexibility to the developer where to enable it. Strict mode can be enabled either on a script level or a function level, by adding the "use strict" statement anywhere at the top of the script or function, for example;

"use strict"; // enable strict mode on a script level. 

function foo() { 

} 

var bar = 4; 

Because the statement "use strict"; by itself is perfectly valid JavaScript (i.e. it initializes a string, but does nothing with it), backwards compatibility is maintained. Your strict-mode-capable-script will still work on all the old versions of IE, albeit in standard mode.

The changes in behaviour introduced in strict mode can be perused in all it’s dry-ness in the ES5 specification, however the changes I’m most excited about are as follows;

  • Assignment of an undeclared variable will throw a ReferenceError rather than create a global variable implicitly.

    foo = 4; // TypeError is thrown
    
  • Invalid assignment of object attributes throw TypeError rather than failing silently. An assignment may be invalid due to the property being Un-[[Writable]] or the object being Un-[[Extensible]].

    var obj = Object.create(Object.prototype, {  // Create an object with an un-writable "x" attribute
        x: {
            writeable: false,
            value: "test"
        }
    });
    
    obj.x = "changed!"; // Throws a TypeError
    
  • Declaring an attribute multiple times via object literal syntax and using the same argument name more than once throws a SyntaxError.

    var obj = {
        foo: "bar",
        foo: "baz" // SyntaxError is thrown
    };
    
  • Using the bad parts of JavaScript such as with, and using caller, callee or arguments attributes throw errors (with throws a SyntaxError, the remainder throw a TypeError).

For further reading on the subject of strict mode, see the MDC article on strict mode.

Leave a Reply

Your email address will not be published. Required fields are marked *