Deep Clone

Zhenghao HeEngineering Manager, Robinhood
Languages

The term "deep clone" is not formally defined in JavaScript's language specification, but is generally well understood in the community. A deep clone makes a copy of a JavaScript value, leading to a completely new value that has no references pointing back to nested arrays or objects in the original value. Any changes made to the deep-copied value should not affect the original value.

Implement deepClone(value) so it returns a deep copy of a JSON-serializable value. The input may be null, booleans, numbers, strings, arrays, or plain objects. It will not contain cycles or special objects like Date, RegExp, Map, or Set. Primitive values can be returned as-is.

Arguments

  1. value (*): The value to clone.

Returns

(*): Returns a deep copy of value.

Examples

const obj1 = { user: { role: 'admin' } };
const clonedObj1 = deepClone(obj1);
clonedObj1.user.role = 'guest'; // Change the cloned user's role to 'guest'.
clonedObj1.user.role; // 'guest'
obj1.user.role; // Should still be 'admin'.
const obj2 = { foo: [{ bar: 'baz' }] };
const clonedObj2 = deepClone(obj2);
obj2.foo[0].bar = 'bax'; // Modify the original object.
obj2.foo[0].bar; // 'bax'
clonedObj2.foo[0].bar; // Should still be 'baz'.

Asked at these companies

Premium featurePurchase premium to see companies which ask this question.
View plans

Loading editor