5

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.

1
  • 3
    Two dates are two different objects, math doesn't apply, specially not in operators, don't confuse them, they have different rules. The date is getting stringified in some cases. Commented May 1, 2014 at 5:06

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Your reasoning does not seem to be correct, namely: new Date(400) >= new Date(401): false.
@AndrewMao Thanks, I wrote the answer off the top of my head, checked it now and found where I erred.
1

Mozilla's documentation for comparison operators in Javascript confirm's Nit's statement about == as defined for variables of type Object.

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

This special note is only made for the operators == and !=. This implies that, for the >= and <= operators, the objects themselves are compared, rather than the internal references.

The natural question is: How is comparison (<, <=, >, >=) defined for two Date objects? I was unable to find any references for this, so I think we might have to look at some source code to answer this question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.