← Questions
Deep clone an object
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Sep 2025. It tests javascript, recursion and objects.
Write a deep clone function for nested JavaScript values without using JSON serialization or a library. Changing anything in the copy must never change the original.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
deepClone(value): returns a deep copy.
It must handle:
- primitives, plain objects and arrays;
-
Map,Set,DateandRegExp; - circular references and shared sub-objects, so two references to the same object in the original point to one shared copy;
- symbol keys and non-enumerable properties, keeping prototypes and property descriptors where possible;
- functions, which are kept by reference, not cloned.
Example
const shared = { n: 1 };
const a = { when: new Date(0), tags: new Set(["x"]), left: shared, right: shared };
a.self = a;
const b = deepClone(a);
b.self === b // true: the cycle points to the copy
b.left === b.right // true: sharing is kept
b.left === a.left // false: it is a new object
b.when.getTime() === 0 // true, and b.when !== a.when
Clarifying questions
- Which built-in types must be supported?
- Must prototypes and getters or setters be preserved, or only plain data?
- How deep can the object graph get?
What a strong answer covers
- A
WeakMapfrom original to copy, checked before cloning each object, which handles both cycles and shared references. - Type dispatch for
Date,RegExp(withlastIndex),MapandSet(cloning keys and values), arrays (including sparse ones) and typed arrays. -
Reflect.ownKeysandObject.getOwnPropertyDescriptorfor symbol keys and non-enumerable properties;Object.create(Object.getPrototypeOf(x)). - Values that need care:
NaN,-0,Infinity. - O(n) time and space; an explicit stack instead of recursion for very deep graphs.
- Tests for each of the cases above.
Follow-ups
- Compare with
structuredClone: what it supports and what it doesn't. - Make it iterative.
- Clone class instances that hold private fields.
Where it's asked
- Apple · Technical phone screen · Last asked Sep 2025
What it tests
javascript · recursion · objects
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
