Reputation: 9151
Why does an object return false
for both true
and false
with the equality operator, but true
when no operator is used?
var test = {
one: "1",
two: "2"
};
if (test) console.log("if"); // true
if (test == true) console.log("true"); // false
if (test == false) console.log("false"); // false
Upvotes: 2
Views: 2797
Reputation: 40970
if(test)
returns true because this condition will return true if test
object is defined/exists. if test
is undefined
or NAN
or null
or false
or ""
it will return false.
And rest of the comparisons are self explanatory as this is
if (test == true)
will return false as test
is not a bool values which can be compare with true
. Instead of this you can try this comparison
if (test["one"] == "1")
console.log("true")
Upvotes: 4
Reputation: 160833
When using ==
, there are rules of type conversion.
So true
and false
is converted to 1
and 0
.
test.toString()
returns string "[object Object]"
which is not equal to 0
nor 1
.
Upvotes: 0
Reputation: 1896
if (test) console.log("if");
returns true because it is checking if object exists/defined.
if (test == true) console.log("true"); // false
if (test == false) console.log("false"); // false
returns false because test is not a Boolean so it cannot be compare to true or false. So it will be always false.
Upvotes: 1