Question

"use strict"; seems awesome, and we'd really like to use it at our shop. However, we just want it so that we (the developers) can find strictness-issues; we very much DO NOT want to make our site break for our actual customers when it was working fine before.

Now, we could just use some server-side logic to achieve this:

{% if debug %}<script>"use strict";</script>{% endif %}

... except that "use strict" operates on a file-by-file basis, so that won't actually work (well, unless we start server-side processing all of our JS files).

So, my question is: do all the things "use strict" checks for get checked when the page loads, or is it possible for "use strict" to find errors after the page has loaded? If it's the former, we can just use "use strict" and stop worrying, because we'll load our site in development before loading it on live. However, if it's the latter we seem to be out of luck, as we can't test every possible runtime condition (and again, we don't want to make errors for our users when there were no errors before).

Was it helpful?

Solution

It's the latter. While beeing in strict mode, an Javascript interpreter may throw error messages at runtime, which would not get thrown in non-strict mode.

On the other hand, most of these errors are "good errors", which means, they will actually help not breaking your code.

For instance

function foo() {
    "use strict";
    bar = true;
}

foo();

This will throw

"ReferenceError: assignment to undeclared variable bar"

in strict mode, which is a good thing. In non strict mode, we would just have created a global variable called bar, which is probably not what we wanted. There are plenty of other situations where strict mode prevents the programmer from doing something stupid/bad/unwanted and throws error messages. But again, you want to have those errors instead of some wierd bugs.

Have a further read on MDN

OTHER TIPS

If I understand you correctly, yes, it's definitely possible for strict mode to catch errors after the page has loaded. For example:

'use strict';

setTimeout(function() {
    undefined = 42; // Causes a TypeError
}, 1000);

// Click here for a demo.

What you can do is pretty simple: you should be minifying your JavaScript when you move to production anyway. Just make sure that the 'use strict' gets removed during that minification process.

Failing that, just try to make sure your code is strict-error-free. Strict mode usually comes into play with regards to semantics, not because of something odd the user input or even because of syntax. It shouldn't be too terribly difficult to catch all the cases. (But minifying and removing 'use strict' is a much better solution.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top