What does “use strict” do in JavaScript?

This is one of the questions I get frequently when delivering workshops on Windows 8 “Windows Store” application development using HTML, CSS and JavaScript.

The use strict is a new feature of the ECMAScript 5, which basically allow us to improve the quality of our JavaScript code, by throwing exceptions when detecting things in our code that we were not supposed to be doing, such as using undeclared variables, using reserved keywords, or using features that are obsolete.

Without enabling this strict mode, the code below is executed without raising any error, even though it is a bad practice to use the variable “name” without declaring it:

function myFunction() {
    name = "Caio Proiete";
    // ...
}

myFunction();

By enabling the “use strict”, an exception will be thrown to notify us that we have a problem in our code:

function myFunction() {
    "use strict";

    // 0x800a13b2 - JavaScript runtime error: Variable undefined in strict mode
    name = "Caio Proiete";
    // ...
}

myFunction();

As expected, as soon as we declare the variable before using it, we no longer get the error “JavaScript runtime error: Variable undefined in strict mode“:

function myFunction() {
    "use strict";

    var name = "Caio Proiete";
    // ...
}

myFunction();

We can enable the strict mode in different scopes: For the entire JavaScript file, for a specific function, or for a specific context. Some examples would be:

(function () {
    "use strict"

    // The entire module is in strict mode

    function a() {
        // this function is in strict mode
    }

    function b() {
        // and this function too...
    }

    // ...
})();
<script type="text/javascript">
    "use strict";

    // This script block is in strict mode
</script>
// ...

<script type="text/javascript">
    // This other script block, in the same file, is *not*
</script>

There are several reasons that will make exceptions to be thrown when using the strict mode, and the goal is always the same: Detect more errors in the code and help the developer.

This is something that we should have always enabled, unless it is not supported. You can see browsers and versions where the “use strict” is supported at the “When can I use…” website.

This entry was posted in JavaScript and tagged , , , . Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>