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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since dates are built-in objects, and not primitives, an equality check is done using the objects references.
In this case, objects
aandbare not the same object, and so the test fails.You can see the same using
By using
.getTimeor.valueOfyou 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
In this case the unary
+operator forces the javascript engine to call the objectsvalueOfmethod – and so it is two primitives that are being compared.