A Case For Linting in JavaScript
JavaScript is a language that allows its users to pretty much do anything syntactically, as evidenced some of my earlier blog posts. But the stranger syntax variations often produce unintended effects. For example, here is a simple checking function:
// The result of reversing an operator var isDefined = function(variable) { return variable !== undefined; }; var isChecked = {}; console.log(isDefined(isChecked));// true console.log(isDefined(isChecked.property));// false
By moving the negation part of the comparison to end it then screws up the function, but throws no error:
var isDefined = function(variable) { return variable ==! undefined; }; var isChecked = {}; console.log(isDefined(isChecked));// false console.log(isDefined(isChecked.property));// false
That is because that is valid JavaScript; The ! operator when used in front of anything negates that thing. Since an empty object is truthy, the negation is false. So when undefined is sent in, it returns false because undefined is not false. This is still valid in strict mode.
But most people who haven't worked with JavaScript resulting in them possibly taking awhile to identify the problem. Especially, considering that ==! is valid negation syntax in other languages. Additionally, this could be caught by tests and isolated. But that relies on tests properly covering key areas of code. In other words what tests your tests?
I think the best way to resolve this is to have a tool that checks all of your code for structural and stylistic issues. I suggest JSHint.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2014/caseForLinting.js













