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