Implement deepClone From Scratch in JavaScript
Implement deepClone from scratch in JavaScript for objects, arrays, dates, maps, sets and circular references, and compare it with structuredClone. Node.js 24.

"Implement deepClone" sounds like a warm-up and turns into a long conversation. The one-line answer, JSON.parse(JSON.stringify(value)), fails for dates, undefined, Map, Set and circular references, and the interviewer knows it. A good answer starts with the requirements, writes a recursive copier for plain data, then extends it step by step to handle the types and the cycles, and ends by pointing at structuredClone, which now does most of this natively. This post follows that path on Node.js 24, with the output of each version, and finishes with the tests and the points to make about what a clone should not copy. For the shallow versus deep distinction in practice, see immutability in JavaScript without a library.
Define what a deep clone is
A shallow copy duplicates the top level and shares everything nested. A deep clone duplicates every level, so changing the clone anywhere never changes the original. For a first version, say that you will clone plain objects and arrays, and that anything else is a decision you will make out loud.
The JSON trick and where it breaks
const original = {
name: "Ana",
joined: new Date(0),
nickname: undefined,
tags: new Set(["a"]),
score: NaN,
nested: { list: [1, 2] },
};
const viaJson = JSON.parse(JSON.stringify(original));
console.log(viaJson);
console.log(viaJson.joined instanceof Date, typeof viaJson.joined);{
name: 'Ana',
joined: '1970-01-01T00:00:00.000Z',
tags: {},
score: null,
nested: { list: [ 1, 2 ] }
}
false stringEvery difference is a bug: the date became a string, nickname vanished, the Set became an empty object and NaN became null. Functions and symbols are also dropped, and a circular reference makes JSON.stringify throw a TypeError. The trick is fine for plain data that came from JSON in the first place, and no more than that.
The recursive version for plain data
function deepCloneBasic(value) {
if (value === null || typeof value !== "object") {
return value;
}
if (Array.isArray(value)) {
return value.map(deepCloneBasic);
}
const copy = {};
for (const key of Object.keys(value)) {
copy[key] = deepCloneBasic(value[key]);
}
return copy;
}
const config = { port: 80, tls: { on: true, ciphers: ["a", "b"] } };
const copy = deepCloneBasic(config);
copy.tls.ciphers.push("c");
console.log(config.tls.ciphers, copy.tls.ciphers);
console.log(copy.tls === config.tls);[ 'a', 'b' ] [ 'a', 'b', 'c' ]
falseThe base case is any primitive, null and functions (typeof gives "function", which fails the !== "object" test, so a function is returned as is). Arrays are mapped, and objects are copied key by key. The copy is independent at every level, as the push shows. Note value === null first, because typeof null is "object" and Object.keys(null) would throw.
This version still has holes, and the interviewer will ask about the first: what about a Date?
const withDate = deepCloneBasic({ at: new Date(0) });
console.log(withDate.at instanceof Date, withDate.at);false {}The date has no own enumerable keys, so it turns into an empty plain object. Every built-in with internal state, such as Date, RegExp, Map and Set, needs its own rule.
Handling built-in types
function cloneValue(value) {
if (value === null || typeof value !== "object") {
return value;
}
if (value instanceof Date) {
return new Date(value.getTime());
}
if (value instanceof RegExp) {
return new RegExp(value.source, value.flags);
}
if (value instanceof Map) {
return new Map([...value].map(([k, v]) => [cloneValue(k), cloneValue(v)]));
}
if (value instanceof Set) {
return new Set([...value].map(cloneValue));
}
if (Array.isArray(value)) {
return value.map(cloneValue);
}
const copy = Object.create(Object.getPrototypeOf(value));
for (const key of Reflect.ownKeys(value)) {
copy[key] = cloneValue(value[key]);
}
return copy;
}
const sample = {
at: new Date(0),
pattern: /ab+/gi,
index: new Map([["x", { n: 1 }]]),
seen: new Set([1, 2]),
[Symbol.for("id")]: 7,
};
const cloned = cloneValue(sample);
console.log(cloned.at.getTime(), cloned.pattern.flags, cloned.index.get("x"));
console.log(cloned.index.get("x") === sample.index.get("x"), cloned.seen.size);
console.log(cloned[Symbol.for("id")]);0 gi { n: 1 }
false 2
7Each type is copied through its own constructor with its internal data, and the contents of maps and sets are cloned recursively. The generic object branch makes three choices worth stating. Object.create(Object.getPrototypeOf(value)) keeps the prototype, so a class instance stays an instance of its class, and its methods still work. Reflect.ownKeys includes symbol keys and non-enumerable ones, unlike Object.keys. And copy[key] = ... assigns a plain data property, so getters are read and turned into values and property attributes such as writable: false are not preserved. A complete clone that keeps descriptors would use Object.getOwnPropertyDescriptors and Object.defineProperties, and you can mention that as the next refinement.
Notice the RegExp copy: lastIndex is not copied, and a regular expression with the g flag keeps state in it. A fresh object starts at zero, which is nearly always what you want.
Circular references
An object that refers to itself makes the recursive version run until the stack overflows.
const node = { name: "a" };
node.self = node;
try {
cloneValue(node);
} catch (error) {
console.log(error.name);
}RangeErrorThe standard fix is a WeakMap from each original to its clone, consulted before copying and filled before descending, so a back reference finds the clone that is already under construction.
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") {
return value;
}
if (seen.has(value)) {
return seen.get(value);
}
if (value instanceof Date) {
return new Date(value.getTime());
}
if (value instanceof RegExp) {
return new RegExp(value.source, value.flags);
}
if (value instanceof Map) {
const copy = new Map();
seen.set(value, copy);
value.forEach((v, k) => copy.set(deepClone(k, seen), deepClone(v, seen)));
return copy;
}
if (value instanceof Set) {
const copy = new Set();
seen.set(value, copy);
value.forEach((v) => copy.add(deepClone(v, seen)));
return copy;
}
const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) {
copy[key] = deepClone(value[key], seen);
}
return copy;
}
const cyclic = { name: "a", children: [] };
cyclic.self = cyclic;
cyclic.children.push({ parent: cyclic });
const twin = deepClone(cyclic);
console.log(twin !== cyclic, twin.self === twin);
console.log(twin.children[0].parent === twin);true true
trueThe key step is seen.set(value, copy) before the loop. When the recursion meets cyclic again, through self or through parent, it finds the clone in the map and reuses it, so the clone has the same shape as the original, cycles included. This also keeps shared references shared: if two properties point at one object, they point at one clone. A WeakMap is the right tool because it holds the originals weakly and is discarded with the call. Note that Reflect.ownKeys on an array includes "length", and assigning copy.length = value.length through the loop is harmless, as length is set to the same number.
What a clone should not copy
Functions are returned as they are. A function cannot be cloned in a way that preserves its closure, so sharing the reference is the only safe choice, and structuredClone throws on them. DOM nodes, promises, WeakMap and WeakSet have no copyable contents and should be rejected or shared. Class instances with private fields (#secret) cannot be copied by property enumeration at all, because the fields are not properties: the clone is created by Object.create without running the constructor, so private fields do not exist on it, and calling a method that uses them throws a TypeError.
class Account {
#balance = 10;
balance() {
return this.#balance;
}
}
const account = new Account();
const clone = deepClone(account);
try {
clone.balance();
} catch (error) {
console.log(error.name);
}TypeErrorThe honest answer to this is to say that classes with private state need their own clone() method, and that a generic deep clone is for plain data.
Compare with structuredClone
Node.js 17 and later, and current browsers, provide structuredClone, which implements the HTML structured clone algorithm.
const data = { at: new Date(0), tags: new Set(["a"]), nested: { n: [1, 2] } };
data.self = data;
const copied = structuredClone(data);
console.log(copied.at instanceof Date, copied.tags.has("a"), copied.self === copied);
try {
structuredClone({ fn() {} });
} catch (error) {
console.log(error.name);
}true true true
DataCloneErrorIt handles dates, maps, sets, typed arrays and cycles, and it throws a DataCloneError for functions. It does not keep prototypes: a class instance becomes a plain object. In production code, structuredClone is the default choice. Writing your own is for an interview or for the cases that need different rules, such as keeping class instances or sharing functions.
Cost and when not to clone
A deep clone allocates a new copy of everything it touches, and the work grows with the size of the data. Cloning a large state object on every keystroke is a common performance bug. Before reaching for a deep clone, ask what you are protecting. If you only change one branch, copy the path to that branch and share the rest, which is cheap and still safe, as long as nobody mutates the shared parts.
Another cost is hidden in the algorithm. structuredClone is implemented by the engine and avoids the overhead of a JavaScript recursion, and a handwritten clone usually cannot match it for large plain data. That is a good reason to use the built-in whenever its rules fit, and to write your own only for the cases it rejects.
Finally, think about what a clone is for. Snapshots for undo, defensive copies at an API boundary and test fixtures all want slightly different rules. A snapshot wants everything, a boundary copy wants only the data and not the methods, and a fixture wants a fresh copy of every nested object so tests cannot affect each other. Naming the purpose first usually settles the questions about functions, prototypes and private fields.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("deepClone copies nested data independently", () => {
const source = { a: [1, { b: 2 }] };
const copy = deepClone(source);
copy.a[1].b = 99;
assert.equal(source.a[1].b, 2);
assert.deepEqual(deepClone(source), source);
});
test("deepClone keeps shared references and cycles", () => {
const shared = { n: 1 };
const source = { x: shared, y: shared };
source.me = source;
const copy = deepClone(source);
assert.equal(copy.x, copy.y);
assert.equal(copy.me, copy);
assert.notEqual(copy.x, shared);
});ℹ tests 2
ℹ pass 2
ℹ fail 0

