4

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".

Philipp Imhof
  • 204
  • 1
  • 7
  • Wow! that's tricky – Ahmad Alfy Jan 30 '22 at 10:52
  • 2
    I believe this qualifies as a linter plugin. A plugin that should warn you whenever you do that – Ahmad Alfy Jan 30 '22 at 10:53
  • Good catch. I can see that JS Fiddle marks `parent` as undefined, based no JSLint – Philipp Imhof Jan 30 '22 at 10:54
  • 1
    Don't use JSLint - it's the oldest linter which doesn't make it bad by itself, but it's *very* strict about rules that don't really matter. All linters after it (JSHint and ESLint) were created in order to provide more freedom in what you consider errors and what not. Rather than just every instance of `++` being as bad as trying to reference a global variable. – VLAZ Jan 30 '22 at 10:56

2 Answers2

5

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    RE ESLint: the [no-implicit-globals](https://eslint.org/docs/rules/no-implicit-globals) rule would catch it. Although I have no idea why it's not part of the recommended set of rules. – VLAZ Jan 30 '22 at 10:59
  • @VLAZ - It doesn't seem to on the demo page, when I enable that option. (It complains about the function being at global scope, but not about `parent in`.) – T.J. Crowder Jan 30 '22 at 11:36
  • Ah, I see. In this case, it's because the variable name is `parent`, so with the config for environment of browser, it classes it as a valid variable, because of `window.parent`. – VLAZ Jan 30 '22 at 14:04
0

No, there isn't anything anything stricter than strict mode.