How to deep copy in JavaScript

In JavaScript, there are two ways to make a copy of an object: a shallow copy and a deep copy. A shallow copy copies the object's properties and values, while a deep copy copies the object's properties and values, as well as its child objects. This article will discuss how to deep copy in JavaScript.

The deep copy constructor function, Object.assign(), is used to create a deep copy of an object. It takes two parameters: the object to be copied and an object that will be used as the prototype for the new object. The prototype object will be used to create new child objects, if necessary.

The following code snippet demonstrates how to use Object.assign() to create a deep copy of an object:

var person = {
name: "john",
age: 30,
job: "software engineer"
};

var copy = Object.assign({}, person);

console.log(copy); 
// {name: "john", age: 30, job: "software engineer"}

The above code will create a copy of the person object, with its own unique properties. The copy object will not have any of the properties or values of the person object.

If you want to create a deep copy of an object, and also copy its child objects, you can use the clone() method. The clone() method is a built-in method of the JavaScript object. It takes one parameter, the object to be cloned.

The following code snippet demonstrates how to use the clone() method to create a deep copy of an object:

var person = {
name: "john",
age: 30,
job: "software engineer",
    address: {
    street: "123 Main St.",
    city: "San Francisco",
    state: "CA"
    }
};

var copy = person.clone();

console.log(copy); 
// {name: "john", age: 30, job: "software engineer", address: {street: "123 Main St.", city: "San Francisco", state: "CA"}}

The above code will create a deep copy of the person object, including its child objects.

💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.