My app behaves abnormally and figured the code below is going to else statement unexpectedly.
code
if(" " != 0) {
console.log("whitespace is not zero");
}
else {
console.log("bar");
}
Firebug output
bar
I thought whitespace is a String and comparison against integer zero should return false like the case above but I don't know why it is going to else statement.
Could anyone explain why?
The other answers have told you how to solve the issue. My answer will attempt to actually explain why you have the issue in the first place (since that was your actual question!)
The behaviour of the
==
operator is defined in the spec as the "abstract equality algorithm". It states (among other things) the following:One of the rules of the
ToNumber
operation on a string is as follows:So we are left with
+0 == 0
which fits another rule of the abstract equality algorithm:This is the case because
0
is the same as+0
. Even if one of the numbers was-0
it would return true:because a string with whitespaces is converted to 0. So To compare:
When you use
!=
rather than!==
, JavaScript tries to coerce the values on either side to the same type. In this case, I think it converts both to numbers." "
happens to be0
as a number. (Try" " * 1
. It evaluates to0
.)This also works with other operators like
>
or*
. So" " > -1
is true and" " * 100
is0
. This also means you can do neat stuff like"6" * "7"
and get42
. Unfortunately, this breaks down with+
since it is inexplicably overloaded to do both math and string concatenation.I personally like all of this behavior except for
+
. Others' opinions vary.In JS,
" " == 0
equalstrue
with loose/lenient comparison, you should use strict equality operator===
/!==
instead:To get to first condition.
Tests:
Loose Comparison Chart:
Strict Comparison Chart:
(Examples by Douglas Crockford)
Good Practice:
Whenever possible, use strict equality operator because with loose equality operator, JS does type coercion which is a performance hit and doesn't always yield expected results as shown in above comparison charts.
to compare with the number 0, you must use the strict comparison
===
a "truth table" found here: Which equals operator (== vs ===) should be used in JavaScript comparisons?