Deep Equality for Dates, RegExp, and Other Built-ins
You'll learn how to correctly compare JavaScript's built-in object types when performing deep equality checks, since reference equality isn't enough.
The Problem with Built-In Objects
When you've been building a deep equality function, you've handled primitives, objects, and arrays. But what about Date, RegExp, Map, Set, and other built-in types? These are objects, but { toString: ... } won't tell you if two dates represent the same moment or if two regexes have identical patterns.
Think of it like comparing two clocks: even if they're different physical objects, they show the same time if their internal mechanisms are synchronized. Similarly, two Date objects are "equal" if they represent the same timestamp, not if they're the same object reference.
How to Compare Built-Ins
Dates: Compare their numeric timestamps using getTime():
function areDatesEqual(a, b) {
return a.getTime() === b.getTime();
}
const date1 = new Date('2024-01-01');
const date2 = new Date('2024-01-01');
console.log(date1 === date2); // false (different references)
console.log(areDatesEqual(date1, date2)); // true (same moment)
RegExp: Compare their source (pattern) and flags:
function areRegExpEqual(a, b) {
return a.source === b.source && a.flags === b.flags;
}
const regex1 = /test/gi;
const regex2 = /test/gi;
console.log(areRegExpEqual(regex1, regex2)); // true
Integration Strategy
In your deep equality function, detect these types using instanceof or checking the object's internal tag, then apply the appropriate comparison logic before falling back to generic object comparison.
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
if (a instanceof RegExp && b instanceof RegExp) {
return a.source === b.source && a.flags === b.flags;
}
Key Takeaway: Built-in types like Date and RegExp require specialized comparison logic—compare dates by timestamp, regexes by source and flags, and apply similar type-specific strategies for other built-ins to achieve true deep equality.