It’s a coercion 🤫
Coercion is the conversion of the values from one type to another. And to understand date comparison, we need to understand how coercion works.
In the previous code example, we have implicit coercion.
When using comparison operators (
>=) there will be an implicit numeric conversion from date object to a number.
This function is called when operators need to convert a Date object to a primitive value.
We have a conversion to a number and that’s why we have:
== will coerce a Date object to a string if the other operand is a primitive value other than
But if we compare 2 objects of the same type, we will compare object references.
that’s why references are not the same
To be sure that we are comparing the same types, we can compare milliseconds. Both
.valueOf() will get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.
.getTime() is converting milliseconds from UTC, we can even compare the dates from different timezones.
We can compare dates, but make sure you know what you are doing.
And you don’t need moment.js for such a small task.
Thanks for reading! If you like the article, give a clap, or two, or 50👏
Leave a comment below if you have any questions or say hi on Twitter.