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?
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With