On this page
The core idea
JavaScript has two equality operators. Strict equality (===) compares without type conversion, while loose equality (==) converts values first, which produces results such as '0' == 0 being true. For objects, arrays and dates, both operators compare references: two separate objects with identical contents are not equal. NaN is not equal to anything, including itself. Safe comparison therefore depends on what you are comparing and why.
A practical approach
Step 1
Use === and !== by default, and enable a linter rule that flags == except for deliberate null checks.
Step 2
Compare dates by their numeric value, for example a.getTime() === b.getTime(), or compare ISO strings in a consistent time zone.
Step 3
Compare objects by the fields that define identity, such as an id, rather than by reference or by stringifying the whole object.
Step 4
Use Number.isNaN() to detect NaN, and Object.is() when you need to distinguish NaN or -0 explicitly.
Step 5
For deep equality in tests, use your test framework's deep-equal assertions instead of writing your own recursive comparison.
Worked example
A wishlist component checks whether a course is already saved with wishlist.includes(course). After data is refetched, the course objects are new instances, so includes always returns false and learners can save the same course twice. Comparing by identifier with wishlist.some(item => item.id === course.id) fixes the duplicates regardless of how the data was loaded.
A mistake to avoid
Do not compare objects with JSON.stringify(a) === JSON.stringify(b). Property order, undefined values and dates all affect the result, so equal data can compare as different and vice versa.
Try it yourself
Write five comparisons that surprise you in the browser console, such as [] == false and new Date(0) === new Date(0). For each, write the safe version and explain why it works.
Your implementation checklist
- Strict equality is the default and enforced by a linter
- Dates are compared by numeric value
- Objects are compared by identifying fields
- NaN is detected with Number.isNaN
- Tests use deep-equal assertions for structures
Share or cite this guide
Innovate with Ajay Editorial (2026-10-07). Compare Values Safely in JavaScript: Equality, Objects and Dates. https://innovatewithajay.com/blogs/compare-values-safely-in-javascript
