DEV3 Technologies home

DEV3 Developer Forum

What is the best way to deep clone an object in JavaScript?

JavaScript helpSolved0 views
dev3 ·

I used JSON.parse(JSON.stringify(obj)) and my Dates became strings and undefined values vanished. What should I use for a proper deep copy?

#javascript#structuredclone#objects

0

1 reply

dev3 · Accepted answer

Use structuredClone, available in all current browsers and in Node.js 17+.

const original = {
  when: new Date(),
  tags: new Set(['a', 'b']),
  map: new Map([[1, { x: 1 }]]),
  nested: { list: [1, 2, 3] },
};
const copy = structuredClone(original);
copy.nested.list.push(4);
original.nested.list; // [1, 2, 3], untouched
copy.when instanceof Date; // true

What it handles

Primitives, plain objects, arrays, Date, RegExp, Map, Set, ArrayBuffer/typed arrays, Error objects and circular references.

What it cannot clone

  • Functions (throws DataCloneError).
  • DOM nodes, class instances lose their prototype (you get a plain object with own properties), getters/setters become data.
  • Symbols as keys are ignored.

Why not JSON

JSON.parse(JSON.stringify(x)) converts Dates to strings, drops undefined, functions and symbols, turns NaN/Infinity into null, and throws on circular structures or BigInt.

Alternatives

  • Shallow copy is often enough: { ...obj }, [...arr], Object.assign. Only top-level properties are copied, nested objects are shared.
  • Update immutably without cloning everything:
const next = { ...state, user: { ...state.user, name: 'New' } };
  • For class instances, add a clone() method or use a library (lodash.clonedeep).

Pitfall: cloning huge objects on every keystroke is slow. Consider structural sharing (spread only the changed path) or Immer.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.