In JavaScript code I want to replace the double-equals structure of the following if-statement:
if( name == null ) {
//do stuff
}
The double equals fail for the jshint rule "eqeqeq", where it's recommended to replace double equals with triple equals. For a moment, let's imagine the above code changed from == null
to === null
like this:
if( name === null ) {
//do stuff
}
This would work for a variable explicitly defined having the value null
, but unfortunately would fail for any unset variables like this.
var a = null; // works correctly
var b; // will fail in comparison
Previously when the triple-equals rule was important to me I would do the following
if( name === null ||| typeof(name) === 'undefined' )
but I find this extremely bloated.
The best alternative I can come up with now is to use the nature of the if-statement and let it evaluate to a false-ish expression like here where I negate the expression and simply remove the == null
part:
if( !name ) {
//do stuff
}
For me, this is much simpler, easy to read, and completely avoids explicit equals comparison. However, I am uncertain if there are any edge causes I am missing out here?
So the question is, can I generally replace == null
with the negated expression if statements? If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
My criteria for picking a solution will be
- clean code
- easy to read and quickly understand
- validates jshint rules
- works in modern browsers (as of writing January 2015)
I am aware of other slightly related questions for discussing difference in the equality operators ==
vs ===
, but this is merely for a discussion of the evaluation compared to null-ish inside the if-statement.
===
rule is vastly overrated, I'd probably just turn it off. – T.J. Crowder===
rule for one other reason: String comparison. Instead I think the strangest thing is that javascript originally introduced both==
and===
. This leads to errors waiting to happen. – Jesper Rønn-Jensen