jsbin started warning me that x != ''
is not good, and I should replace it with x !== ''
Why?
jsbin started warning me that x != ''
is not good, and I should replace it with x !== ''
Why?
var x = false;
console.log(x !== ''); //true
console.log(x != ''); //false
In other words, false
(and other falsy values, like 0
) will coerce to an empty string. The !==
and ===
operators (strict equality operators) ensure that the things being compared are of the same type.
To expand upon why this is the case, you need to head to the spec (linked to by T.J. Crowder in the comments). The section on the "Abstract Equality Comparison Algorithm" tells us the following:
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
The section on ToNumber
tells us:
The result is 1 if the argument is true. The result is +0 if the argument is false.
In the example above, the argument is false
, so we are now comparing +0 != ''
. When comparing a number to a string, the following rule is followed:
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
Calling ToNumber
on an empty string results in +0
, just as it did for false
:
A StringNumericLiteral that is empty or contains only white space is converted to +0.
Now we are comparing +0 != +0
, so we enter the "x and y are of the same type" section, which tells us:
If x is the same Number value as y, return true.
So +0
is equal to +0
and since we are using !=
it returns false
.