Why using `strict mode` in JavaScript libraries? [duplicate]

The question you linked, its answers, and the references it gives list a bunch of reasons for using strict mode.

Let me call out just one of them: The Horror of Implicit Globals¹

Non-strict code:

function foo(a) {
    var myvar;

    myar = a * 4;

    // ...

    return myvar;
}

Now, this code:

console.log(foo(2));

…should log “8”, right? But it doesn’t, it always logs “undefined”:

function foo(a) {
    var myvar;

    myar = a * 4;

    // ...

    return myvar;
}
console.log(foo(2));

And what’s more, it silently creates a global variable called myar. Why? Because I had a typo in my code (I missed out the v in myvar when setting it to a * 4).

Compare with:

function foo(a) {
    "use strict";
    var myvar;

    myar = a * 4;

    // ...

    return myvar;
}
console.log(foo(2));

Now, instead of a weird return value and a global variable getting created, I get a nice error message: ReferenceError: "myar" is not defined

Now, that particular aspect of strict mode could be accomplished using a lint tool instead. But you don’t always involve a lint tool in your coding-in-anger toolchain, when you’re just trying to fix something and bouncing between your editor and the browser. So it’s nice when the browser helps you out.

Separately, strict mode does things that can’t be done by lint tools, such as disallowing with, changing the default value of this in function calls that don’t set it, etc.


¹ (that’s a post on my anemic little blog)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)