Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new Date(), compare confuse [duplicate]

Tags:

javascript

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
like image 650
Alexander Tolstikov Avatar asked Oct 14 '25 14:10

Alexander Tolstikov


2 Answers

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).

like image 68
Pointy Avatar answered Oct 17 '25 11:10

Pointy


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)
like image 30
charlietfl Avatar answered Oct 17 '25 09:10

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!