11

Why does the equality operator return false in the first case?

var a = new Date(2010, 10, 10);
var b = new Date(2010, 10, 10);
alert(a == b); // <- returns false
alert(a.getTime() == b.getTime()); // returns true

Why?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Art
  • 23,747
  • 29
  • 89
  • 101

4 Answers4

28

Since dates are built-in objects, and not primitives, an equality check is done using the objects references.

In this case, objects a and b are not the same object, and so the test fails.
You can see the same using

var a = new String("a");
var b = new String("a");
alert(a == b); //false

By using .getTime or .valueOf you are converting the objects value into a primitive, and these are always compared by value rather than by reference.

If you want to do a comparison by value of two dates there is also a more obscure way to do this

var a = new Date(2010, 10, 10);
var b = new Date(2010, 10, 10);

alert(+a == +b); //true

In this case the unary + operator forces the javascript engine to call the objects valueOf method - and so it is two primitives that are being compared.

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
0

Compare two dates with JavaScript

dates.compare(a,b)

The fact is that the comparison between the two objects does not work properly :/

Community
  • 1
  • 1
Alfabravo
  • 7,493
  • 6
  • 46
  • 82
0

If you create two clocks, and set them both to the same time, you have two clocks.

If you change the time in one clock, it will not change the time in the other clock.

To compare or sort Dates, subtract one from the other. The valueof a Date object, used in a mathematical expression, is its timestamp.

function compareDates(a,b){return a-b};

kennebec
  • 102,654
  • 32
  • 106
  • 127
-1

I'm sorry guys, but this is idiotic... especially the bit about having two clocks.

==, by definition compares VALUES, whereas === compares references. Saying that == fails for non-primitives breaks the language's own syntactical structure. Of course, === would fail in the initial example, as the two dates are clearly two distinct pointers to two distinct memory-spaces, but, by the very definition of the JS spec, == should return TRUE for the comparison of two dates whose value is the same point in time.

Yet another reason I hate JS...

Sorry to rant, but this just kicked my butt for an hour.

As an aside, you can use valueOf() to force the comparison of the values, and that will return true... it is redundant with == but it works.

user505150
  • 15
  • 1
  • 1
    You do not know what you are ranting about... The distinction between == and === has nothing to do with values vs refs, == simply states that the VM should use a set of clearly defined coercing rules when the two operands are of different types, while === states that no such coercion is to occur. – Sean Kinsey May 19 '11 at 10:19