According to the ECMA script standard, the following code should return true, but it doesn't:
d = new Date() ;
d.setTime(1436497200000) ;
alert( d == 1436497200000 ) ;
Section 11.9.3 says:
- If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
Then, section 8.12.8 says that ToPrimitive
retuns the result of the valueOf
method. Which means that the last line in my example above should be equivalent to:
alert( d.valueOf() == 1436497200000 );
Which does return true
, indeed.
Why does the first case not return true
?
Strict equality using ===Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal.
To summarize comparison of equality is used to show that two things, people are similar. There is no difference between the subject and the object. It can be used with adjectives, adverbs and nouns.
=== (Triple equals) is a strict equality comparison operator in JavaScript, which returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 2 with “2” using ===, then it will return a false value.
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
If you look at the spec at section 8.12.8, you will find this text near the end of the section:
When the
[[DefaultValue]]
internal method ofO
is called with no hint, then it behaves as if the hint wereNumber
, unlessO
is aDate
object (see 15.9.6), in which case it behaves as if the hint wereString
.
(Emphasis mine)
Now, in step 8
/ 9
of the The Abstract Equality Comparison Algorithm [11.9.3], ToPrimitive(x)
and ToPrimitive(y)
are called without hint
parameter.
The lack of this hint
parameter, together with the above text, means that the ToPrimitive
method returns the toString()
value, on date objects.
As you're probably aware, (new Date()).toString()
returns a string representation of the date in American English [source]:"Wed Jul 01 2015 22:08:41 GMT+0200 (W. Europe Daylight Time)"
That a string like that doesn't equal 1436497200000
shouldn't come as a big surprise. ;-)
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