Jonathan
Jonathan

Reputation: 9151

Object returns `false` for both `true` and `false` with the equality operator

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

FIDDLE

Upvotes: 2

Views: 2797

Answers (3)

Sachin
Sachin

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")

Js FIddle Demo

Upvotes: 4

xdazz
xdazz

Reputation: 160833

When using ==, there are rules of type conversion.

  • If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and 0 if it is false.
  • If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.

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

Rajesh Dhiman
Rajesh Dhiman

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

Related Questions