Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Javascript comparison operators mathematically inconsistent?

In a math class a long time ago I was taught that

a == b if and only if a <= b and b <= a.

Javascript doesn't seem to think so:

> new Date(400) <= new Date(400)
true
> new Date(400) >= new Date(400)
true
> new Date(400) == new Date(400)
false

Can someone explain the type coercion rules that lead to this result? It seems that the fuzzy equal to operator == should believe that the two Dates have equal values.

like image 274
Andrew Mao Avatar asked Oct 01 '22 21:10

Andrew Mao


1 Answers

Firstly let's start with what you're comparing:

typeof new Date(400)
"object"

Javascript objects use the method .valueOf() to compare the values in the first two cases. General objects don't know how to compare one to another by default and use the string "[object Object]". Dates on the other hand know how to.

new Date(400) <= new Date(400)
new Date(400).valueOf() <= new Date(400).valueOf()
400 <= 400
true

However, the last operation is defined for objects differently, it compares if the two objects (not the integers as above) have the same reference, which they won't as both of them are separately created new objects.

new Date(400) == new Date(400)
false

If you want to compare the date values in a similar manner to your first two, you'll need to instead specifically call .valueOf().

new Date(400).valueOf() == new Date(400).valueOf()
true
like image 68
Etheryte Avatar answered Oct 07 '22 21:10

Etheryte