# Deep Copy

> The Deep Copy in JS is a process of creating a new object that duplicates an existing object, including all nested objects, without affecting the original.

## How do I deep copy an object in JavaScript?

The process of creating a new object that is a complete copy of an existing object, including all nested objects. It ensures that changes to the new object don't affect the original object.

- Topic: Basics
- Type: concept

## Example

Wrong:

```js
const copy = JSON.parse(JSON.stringify(order));
copy.createdAt.getTime(); // TypeError
```

Right:

```js
const copy = structuredClone(order);
copy.createdAt.getTime(); // works
```

`structuredClone()` keeps dates, maps, sets and cycles that a JSON round trip breaks.

## Common mistakes

- Losing `Date`, `Map` or `undefined` values after a JSON round trip.
- A `DataCloneError` when the object contains a function.

## Key points

- Deep copies use `structuredClone()`, not `JSON.parse(JSON.stringify())`.
- Data passed to `structuredClone()` has no functions, DOM nodes or class instances that must keep their prototype.
- Only data that will be changed independently is deep copied.

## Interview questions

### Why not use JSON.parse(JSON.stringify()) for deep copy?

It turns dates into strings, drops `undefined` and functions, loses `Map` and `Set`, and throws on circular references.

### Does structuredClone copy class instances?

It copies own data properties, but the result is a plain object without the class prototype or methods.

## Related cards

- [structuredClone()](https://wonderium.dev/js/structured-clone.md)
- [Shallow Copy](https://wonderium.dev/js/shallow-copy.md)
- [JSON](https://wonderium.dev/js/json.md)
- [Primitive Values and Reference Values](https://wonderium.dev/js/primitive-values-and-reference-values.md)
- [Map](https://wonderium.dev/js/map.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/deep-copy
- Last updated: 2026-11-25
