Why is (new Date() == new Date()) false, but (Date() == Date()) is true? [duplicate]

半城伤御伤魂 提交于 2019-12-05 20:15:09

Using Date(), the JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object. MDN Reference.

typeof Date()    //"string"
Date() == Date() //true

Using instead a constructor as new Date(), each instance is unique (the two instances of the same constructor are still different to each-other), this is the reason why they are not equal when compared.

typeof new Date();        //"object"
new Date() === new Date() //false

Simply put, Case 2 returns false because you are comparing two different object references (even if both objects contain the exact same properties).

Whereas in the other cases you are comparing the toString() value of the dates.

Please see Note 3 in the official documentation for the == Abstract Equality Algorithm

NOTE 3

The equality operator is not always transitive. For example, there might be two distinct String objects, each representing the same String value.

Each String object would be considered equal to the String value by the == operator, but the two String objects would not be equal to each other. For Example:

new String("a") == "a" //true

"a" == new String("a") //true 

but

new String("a") == new String("a") //false.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!