javascripterror-detection

JavaScript: prevent unintentional creation of new property


Typos happen, and sometimes it is really hard to track them down in JavaScript. Take this for example (imagine it in between some more code):

// no error. I would like a warning
document.getElementById('out').innerHtml = "foo";

For undeclared variables, strict mode helps:

"use strict";
var myHTML = "foo";
myHtml = "bar"; // -> error

But it does not work for the example above. Is there a program or mode that can catch these bugs? I tried JSLint and JavaScript Lint, but they do not catch it.

And ideally, I would like this to still work (without warning):

// should work (without warning)
function MyClass(arg) {
  this.myField = arg;
}

Solution

  • Using an IDE like WebStorm helps a lot in detecting this kind of errors.

    To prevent accidentally adding properties to an object, you can freeze it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

    With ES6, you could use proxies to detect these errors: http://www.nczonline.net/blog/2014/04/22/creating-defensive-objects-with-es6-proxies/