I ran in to this error a moment ago, produced by JSHint:
The error says: Confusing use of ‘!’
That was certainly a new one to me… but after a moment of thought, it made sense.
The Potential Confusion
Here’s the original code that I wrote, which produced this problem:
Does this code say “(not id) in ticket”, or is it saying “not (id in ticket)”?
A Less Confusing Version
Let’s clean this up so it’s less confusing.
In this version of the code, I’m explicitly grouping the “in” statement before running the “!” (not) statement. The code is significantly more clear, already. I also avoided the JSHint error, which is what my ultimate goal was in this case.
If I want to take this one more step, however, I can make the code even more clear.
In this version, I explicitly make the “in” check and assign it to a variable. Now my if statement is even easier to understand because I have given a name to the operation being performed.
Naming A Concept
Reading “!hasId” is easier for our mind to parse and understand as “not has id”, than “not id in ticket”. We’ve given a name to the concept that is expressed in the code.
This form of abstraction (named variable representing an operation result) is the basis by which we understand everything around us. You don’t look at a bottle of water and think about chains of polycarbons, hydrogen atoms, etc. You think “bottle of water”.
Named abstractions are an important part of the way we think, and should be reflected in our code.
Of course this can go too far. Sometimes there isn’t a proper name for a line of code, and many times that line of code is already wrapped in a named function, which covers the concept.
Taking this idea too far is just as bad as not taking it far enough. The key is to find the balance where names are meaningful and representative of what’s going on, not just names for the sake of naming things.
P.S. If you’re interested in seeing how I set up and use JSHint, check out my WatchMeCode episode on using JSHint from Grunt.