Deep Equal For Nested Objects
Compare nested objects for deep equality handling arrays dates maps and circular references without stack overflow.
Code
export function deepEqual(a,b,seen=new WeakSet()){if(a===b)return true;if(a===null||b===null||typeof a!=='object'||typeof b!=='object')return false;if(seen.has(a)||seen.has(b))return a===b;seen.add(a);seen.add(b);if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return false;return a.every((v,i)=>deepEqual(v,b[i],seen));}if(a instanceof Map&&b instanceof Map){if(a.size!==b.size)return false;for(const[k,v]of a)if(!b.has(k)||!deepEqual(v,b.get(k),seen))return false;return true;}const ak=Object.keys(a),bk=Object.keys(b);if(ak.length!==bk.length)return false;return ak.every(k=>deepEqual(a[k],b[k],seen));}How it works
Deep Equal For Nested Objects keeps everything in the function deepEqual.
Watch out for
- The guard
a===bshort-circuits the flow with an earlyreturnwhen its condition holds.
Taking the usage further
Signature: export function deepEqual(a,b,seen=new WeakSet()
Import deepEqual from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `deepEqual` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.