Copying and Comparing

Shallow Copy, Deep Copy and Comparison (structuredClone)

Assignment copies only a reference. Spread and Object.assign() copy one level, so nested objects stay shared. structuredClone(), a global in browsers (Baseline since March 2022) and Node.js 2,131 , deep-copies with the algorithm postMessage() uses. === never compares contents, and comparing JSON.stringify() output fails when key order differs: use isDeepStrictEqual() in Node.js or Lodash 61,278 's isEqual() in the browser.

Four ways to copy an object (none keeps the prototype)
Technique Nested Date, Map Cycles Functions
b = a shared shared shared shared
{ ...a } shared shared kept copied
JSON round trip copied string, {} throws dropped
structuredClone copied copied kept throws
Shallow copy, structuredClone and deep comparisonJavaScript
import { isDeepStrictEqual } from "node:util";
const original = { tags: ["js"], created: new Date(0) };
original.self = original;
const shallow = { ...original }, deep = structuredClone(original);
shallow.tags.push("css");                   // shared array: original changes too
console.log(original.tags, deep.tags, deep.created instanceof Date, deep.self === deep);
try { structuredClone({ f() {} }); } catch (e) { console.log(e.name); }
console.log({ a: 1 } === { a: 1 }, isDeepStrictEqual({ a: [1] }, { a: [1] }));
Output
[ 'js', 'css' ] [ 'js' ] true true
DataCloneError
false true