What is the difference between if (!x)
and if (x == null)
; that is, when can their results be different?
Say x is a string.
x = undefined;
if(!x) {
alert("X is not a truthy value");
}
if(x == null) {
alert("X is null");
}
x = "";
if(!x) {
alert("X is not a truthy value");
}
if(x == null) {
alert("X is null");
}
x = null;
if(!x) {
alert("X is not a truthy value");
}
if(x == null) {
alert("X is null");
}
You'll notice that "X is not a truthy value" is shown in all three cases, but only in the case of X being undefined or null is "X is null" shown.
When X is a boolean value, then (!x)
will be true when X is false but (x == null)
will not be. For numbers 0 and NaN are considered false values, so not X is truthy.
See it in action, including the difference between ==
(equality using type conversion) and ===
(strict equality)