Proper Ways to Clone an Object in JavaScript
Tags: webdev, beginners, javascript, node
Published: 2020-07-22 08:51:47

---
title: Proper Ways to Clone an Object in JavaScript
published: true
date: 2020-07-22 07:31:40 UTC
tags: webdev,beginners,javascript,node
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/1000/0*3MBOGQB4P2dtrBud)<figcaption>Photo by <a href="https://unsplash.com/@bedeviere?utm_source=medium&amp;utm_medium=referral">Bimata Prathama</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

Objects in JavaScript are reference values and can store complex key-value properties.

```js
let story = {
    title: 'Proper Ways to Copy(Clone) an Object in JavaScript',
    author:{
            name:'pkoulianos',
            email:'petran@pkoulianos.com'
    },
    tags:['Javascript','programming']
};
```

Copy an object can be a little tricky. But don’t worry about in this story we’ll cover how to copy an object in proper ways.

### 1. The Fatal😡 Way to Copy an Object

A fatal way to try copying an object is to use the assign = operator. The reason is that the assign operator will only pass the reference to the new variable.

Let’s see a simple example

```
let car1 = { color:’white’, type:’4X4'};// fatal way to copy an object
let car2 = car1;//change the color property
car2.color = ‘red’;console.log(car1);
**//{ color: 'red', type: '4X4' }** 😂😂
console.log(car2);
**//{ color: 'red', type: '4X4' }** 😂😂
```

In the above example, we create a new object car1 and try to copy it with the = operator to a new variable car2 and we change the color property. Printing both objects we can see that is identical and the reason is that both car1 and car2 have the same reference of the object.

### 2. Get a Shallow💧 copy

> [_Shallow copy_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _will copy all_ [_enumerable_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable) [_own properties_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) _from the source object to the target._

In simple terms, a shallow copy **will not** truly copy :

1. Arrays, Sets, etc
2. Inner objects

Get a shallow copy with Object.assign()

Object.assign() will get you a shallow copy of your target object:

```
let post = {
   title:'How to copy objects in JS',
   tags:['js','js-basics','programming'],
   date: new Date(),
   author:{
         name:'petros',
         email:'petran@pkoulianos.com'
   },
   getAuthorData: function(){
              return this.author.name+'-'+this.author.email;
   }
};let newPost = Object.assign({},post);
newPost.title = 'I love js'
newPost.tags[0] = 'web-programming'
newPost.author.name = 'Petran';
newPost.date = new Date(1970);console.log(post);
console.log(newPost);//console output
{ title: 'How to copy objects in JS',
  tags: ['web-programming', 'js-basics', 'programming'],
  date: 2020-07-21T18:48:29.112Z,
  author: { name: 'Petran', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' },
  getAuthorData: [Function: getAuthorData] }
{ title: 'I love js',😀
  tags: ['web-programming', 'js-basics', 'programming'],😂
  date: 1970-01-01T00:00:01.970Z,😀
  author: { name: 'Petran', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' },😂
  getAuthorData: [Function: getAuthorData] }😀
```

In the above example, we create a new object post and copy it with Object.assign() to a new variable newPost and we change all properties. Printing both objects we can see that the shallow copy newPost have copied properly the title ,date and getAuthorData but tags and author are pass by reference.

### Get a shallow copy with …Spread operator

The spread operator will get you also a shallow copy of your target object:

```
/ \*\*\* / 
**let newPost = {...post}**
/ \*\*\* /
console.log(post);
console.log(newPost);//console output
{ title: 'How to copy objects in JS',
  tags: ['web-programming', 'js-basics', 'programming'],
  date: 2020-07-21T18:48:29.112Z,
  author: { name: 'Petran', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' },
  getAuthorData: [Function: getAuthorData] }
{ title: 'I love js',
  tags: ['web-programming', 'js-basics', 'programming'],
  date: 1970-01-01T00:00:01.970Z,
  author: { name: 'Petran', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' },
  getAuthorData: [Function: getAuthorData] }
```

### 3. Get a Deep🌊 copy

A deep copy of an object will solve the mystery of getting a proper copy of inner objects and arrays, sets, etc **but date objects will be converted to string and functions will not be copied at all.**

We can get a deep copy by using the JSON object.

**let targetObj = JSON.parse(JSON.stringify(sourceObj));**

```
/ \*\*\* / 
let newPost = JSON.parse(JSON.stringify(post));
/ \*\*\* /
console.log(post);
console.log(newPost);//console output
{ title: 'How to copy objects in JS',
  tags: ['js', 'js-basics', 'programming'],
  date: 2020-07-21T18:54:35.964Z,
  author: { name: 'petros', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' },
  getAuthorData: [Function: getAuthorData] }
{ title: 'I love js',
  tags: ['web-programming', 'js-basics', 'programming'],
  date: **'2020-07-21T18:54:35.964Z'** ,😂
  author: { name: 'Petran', email: '[petran@pkoulianos.com](mailto:petran@pkoulianos.com)' } }
```

Printing both objects we can see that the deep copy newPost have copied properly the title , tags and author but date is converted to string and getAuthorData are not copied at all.

### 5. Conclusion

Both Shallow and Deep copies have their own pros and cons. Before we decide which copy is right, we have to be sure about the object properties.

### References

- [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Object/assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)

* * *