Cynical
Cynical

Reputation: 9568

Compare Object and Boolean has different results using `!=` and `==`

I'm having trouble understanding the behaviour of the equality operator in JavaScript. This is what I get when I run the following commands on a browser's console:

new Object() == true  // returns false
new Object() != false // returns true

Now, I don't agree with the fact that an Object should be false (although I have understood why after checked the ECMAScript Language Specification), but what really bothers me is that I get two different results on two equivalent logical expressions.

What's happening?

Upvotes: 3

Views: 218

Answers (2)

Mark
Mark

Reputation: 92440

According to the spec, both of these should return false (this aligns with common sense to me):

new Object() == true  // false
new Object() == false // false

based on:

  1. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

  2. Return false.

Since they both return false and:

A != B is equivalent to !(A == B).

both of these should be true:

new Object() != true  // true
new Object() != false // true

note: This shouldn't be confused with the truthiness of new Object(). In other words new Object() == true is not the same Boolean(new Object()) == true

Upvotes: 1

Quentin
Quentin

Reputation: 943216

You linked to this which gives a 10 step list of things to check based on what the left and right-hand sides are.

The left-hand side is an object. The right-hand side is a boolean.

This means that it hits step 10:

Return false.

An object is not equal to true nor is it equal to false.

Upvotes: 1

Related Questions