JavaScript: Clone, Deep Copy Object/Array

By Xah Lee. Date: . Last updated: .

Deep Copy

Here's the best way to clone (deep copy) a object. Object can be type Array or Object.

/* [
xah_deep_copy_array_or_object(obj) deep copy/clone a object.
This is the best way. fastest too.
http://xahlee.info/js/js_clone_object.html
Version 2017-01-30.
] */
const xah_deep_copy_array_or_object = ((obj) => JSON.parse(JSON.stringify(obj)));

[see JSON]

Shallow Copy

For shallow copy, use the slice method with no argument. This is same as clone if your array does not contain elements that are references (that is, other array or objects.).

const oldArray = [3,4,5];

// shallow copy
const newArray = oldArray.slice();

[see Array.prototype.slice]

What's the Difference Between Deep Copy and Shallow Copy?

Shallow copy copies by reference of nested elements. This means, if you have shallow copy, changing a nested object may also change your copy.

// shallow copy isn't true clone

const mm = [8];

const aa = [3,mm];

// shallow copy
const bb = aa.slice();

mm[0] = 4;

// both are changed
console.log(aa); // [ 3, [ 4 ] ]
console.log(bb); // [ 3, [ 4 ] ]

JavaScript Object and Inheritance

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc