Checking Date Equality in JavaScript

When working with dates, one of a programmer's most common needs is to check whether one date matches another. And if you're like most programmers, the first way that you thought of doing it is something like this:

The reason it will never return true is because of the way object equality works in JavaScript. Object equality isn't tested by the internal value of the object, but by identity. In other words, if it isn't the exact same copy of the Date object, it isn't considered equal.

To make our isChristmas function work, we need to check equality in a different way.

Despite the "gotcha" of getMonth returning a 0-indexed number for months, this function now works. However, it doesn't take into account the complexities of timezones and working with local time versus UTC/GMT time.

Because of these complexities, it is generally better to lean on a robust and well-tested library like Moment.js to do things like date comparisons.

But most importantly, now you know not to count on JavaScript's equality operators when comparing dates.

Thanks for reading!

Josh Clanton

Want to improve your JavaScript skills?
Subscribe to A Drip of JavaScript for biweekly tips to help you level up as a JS developer.