I am implementing a seemingly trivial utility function to check if a value is null
or undefined
.
My original implementation looked like this:
function isNil(value) {
return value === null || value === undefined;
}
I then looked up Lodash's implementation:
function isNil(value) {
return value == null
}
On the surface, this would seem like a naiive approach since it violates eslint's eqeqeq rule as well as only checking for null
.
I'm guessing that this approach works due to a combination of JavaScript's truthiness and equality rules, but is there actually an advantage to Lodash's implementation?
value === null || value === undefined
and value == null
are equivalent as can be seen in the specification of the Abstract Equality Comparison Algorithm:
The comparison
x == y
, wherex
andy
are values, produces true or false. Such a comparison is performed as follows:[...]
- If
x
is null andy
is undefined, return true.- If
x
is undefined andy
is null, return true.
The "eqeqeq" rule of ESLint is not relevent as it is just for linting, it does not enforce anything in ECMAScript itself. And lodash does not use that rule.
Technically, there is no real advantage as it has the exact same outcome. One might argue value == null
could be faster as it does only do one equality check and does not perform up to two calls of the Strict Equality Comparison Algorithm like your first example. It does most probably not matter at all as even if there was a difference, it would be very small.
Personally, I would use the value === null || value === undefined
as it is clearer and does not even need a documentation. Besides, tools like uglify could easily replace value === null || value === undefined
with value == null
for production.