Reputation: 2061
Jshint is not pleased with this expression:
var amount = $('.some-input').val()
// Check for NaN or <= 0
if (!(+amount > 0)) {
...
}
It claims confusing use of !. Is there a way to rewrite the expression without adding too much code?
Upvotes: 1
Views: 148
Reputation: 816334
The equivalent without the negation is:
if (amount <= 0 || isNaN(amount)) {
So, instead of saying "Is not greater than", you are saying "Is less than or equal". Additionally, not everyone might know that NaN
cannot really be compared to numbers (i.e. always returns false
) and hence an explicit test can make this expression easier to read and understand overall.
Apparently humans find negations more difficult to understand and I would not say that there is no truth to it.
Upvotes: 6
Reputation: 382112
You could write
if (amount > 0 === false) {
The string is automatically converted to a number when in this comparison, and any string that can't be correctly parsed as a number is converted to NaN
which isn't >0
. And jshint seems to be pleased when it sees === false
in place of the convenient !
.
But the real solution seems to not use jshint, which isn't pertinent here. This tool doesn't let you use the power of JavaScript.
If you decide to drop jshint, I'd still advise you to simplify a little your test as
if (!(amount > 0)) {
Quality wise, the most important here would be in my opinion the small comment you already added.
Upvotes: 2