Say I want to check if a value v
is either null
or undefined
in
JavaScript. I might use this conditional:
if (!v) { ... } // 🙅♀️ wrong!
Because of JavaScript's weak typing, this conditional will catch way
more than just null
and undefined
.
Instead, use this:
if (v == undefined) { ... } // ✅ right!
This uses the weakly-typed ==
to our advantage. According to the
ECMAScript spec, x == y
is true when x
is null
and y
is
undefined
; trivially, it's also true when x
and y
are the exact
same value (e.g.,. both x
and y
are undefined
). This behaviour is
explicit in the definition of ==
, so this is one of the only times
I prefer to use ==
over the far stricter (and safer) ===
comparison.
I've listed here a bunch of different values of v
and the results of
!v
and v == undefined
:
v |
desired | !v |
v == undefined |
---|---|---|---|
undefined |
true |
true |
true |
null |
true |
true |
true |
0 |
false |
true |
false |
false |
false |
true |
false |
'' |
false |
true |
false |
NaN |
false |
true |
false |