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;
}
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/
Well, thats the price of dynamically typed programming languages. because it is possible to add properties at runtime, there is no real solution to detect typos in code.
you could however add an innerHtml
function to the Element
prototype, internally calling innerHTML
to eliminate certain typos, but I definately wouldn't recommend that.
As other comments already suggested: A good IDE can help you identifiying typos. I'm only working with WebStorm and VisualStudio which both are able to detect undeclared or unused functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With