Can anyone explain this unexpected behavior?
console.log(new Date() == new Date()); // false
console.log(new Date() >= new Date()); // true
console.log(new Date() <= new Date()); // true
The ==
comparator compares the object references, and two different objects will never be equal.
The relational comparators, however, will compare the numeric values of the dates (the underlying timestamps). Thus if you tried
new Date().getTime() == new Date().getTime()
you'd get true
. In this case, the =
part of the >=
and <=
operators makes the statements true (as in the example above).
The first is comparing equality of 2 different objects.
The >=
and <=
will first coerce the Date objects to Number
Simplified resultant example:
{} == {} // false
41765490 <= 41765490 // true
41765490 >= 41765490 // true
For the first case of ==
you can also force the coersion to number doing:
+new Date() == +new Date() // true (assuming no lag between creating both)
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