Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality comparison between Date and number doesn't work

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:

  1. 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?

like image 613
GetFree Avatar asked Jul 01 '15 19:07

GetFree


People also ask

Are strict equal identical?

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.

What is equality comparison?

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.

Why use triple equals JavaScript?

=== (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.

What is strict equal in JavaScript?

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.


1 Answers

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 of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see 15.9.6), in which case it behaves as if the hint were String.

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

like image 152
Cerbrus Avatar answered Sep 30 '22 00:09

Cerbrus