Search code examples
javascriptdateequality

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


I have been messing around with JSFiddle to solve this problem in FreeCodeCamp. When I use Date as a string (i.e., no "new"):

Case 1:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = Date()
  let tomorrow = Date()

  console.log(today)
  console.log(tomorrow)
  console.log(isSameDay(today, tomorrow))

isSameDay returns true. However when I use Date as a constructor (with "new"):

Case 2:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = new Date()
  let tomorrow = new Date()

  console.log(today)
  console.log(tomorrow)

  console.log(isSameDay(today, tomorrow))

isSameDay returns false. However(!), when I add the unary operator "+":

Case 3:

function isSameDay (dtFrom, dtTo) {
    return dtFrom == dtTo
  }

  let today = + new Date()
  let tomorrow = + new Date()

  console.log(today)
  console.log(tomorrow)

  console.log(isSameDay(today, tomorrow))

isSameDay returns true. I understand case 1 and case 3 returning true because they are just the same strings and the same millisecond values.

Why does case 2 return false?


Solution

  • 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