Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stricter than strict mode?

I recently produced a stupid bug:

"use strict";

function doSomething() {
    let testObject = {a: "foo", b: "bar", parent: "bla"};

    if (parent in testObject) {
        console.log("has a parent")
    }
    else {
        console.log("does not have a parent")
    }
}

doSomething();

Due to the missing quotes around the literal parent, the interpreter accessed window.parent and there was no ReferenceError as there would have been had I written a in testObject.

Obviously, JavaScript could not know that I my intention was not to access window.parent and thus could not have thrown an error. But I wonder whether there is some sort of debugging mode that would output a warning to the console in such cases, something along the line: "parent is not defined in this scope, accessing the global variable instead".

like image 623
Philipp Imhof Avatar asked Oct 17 '25 22:10

Philipp Imhof


1 Answers

No, JavaScript doesn't have a "stricter" mode that would have warned you of this. Some linters might (though ESLint doesn't seem to, at least with the demo page's default settings).

TypeScript would have, though (example), since window.parent isn't a string or Symbol, so doesn't make sense as the left-hand operand of in. Adopting TypeScript has costs, of course, but it does have benefits like this.

like image 84
T.J. Crowder Avatar answered Oct 19 '25 10:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!