Select Page

How to Copy an Object in JavaScript – JavaScript Object Cloning

by | Jun 19, 2023

To copy object in JavaScript, we often use techniques like shallow and deep copying. This is necessary to preserve data, ensure immutability, achieve reference independence, modify complex structures, and facilitate comparison and testing.

What is an Object in JavaScript?

An object in JavaScript is a collection of key-value pairs, and it is a non-primitive data type. Why it is a non-primitive data type? Because the object may contain different data types.

Let’s dive into an example:


const car = {
  model: "Fiat",
  year: 2006,
  miles: 200 000
}

Whenever working with objects we may get into a situation to need to change some of the values or add additional properties to the object.

Considering the example from above imagine we have used the car and drove additional 100 miles. Then we should update the miles property from 200 000 to 200 100.

In some work cases, we will get into a situation where we might need to make a copy of the object before updating it’s properties.

Let’s dive into the different ways of creating a copy of the object.

Copy object in JavaScript

Copy object in JavaScript using = operator

const newCar = car
consol.log(newCar) // {model: "Fiat", year: 2006, miles: 200 000 }

When we print this new copy of the object everything looks okay but let’s dive deeper into what happens if we modify some of its properties.

newCar.miles = 200 100
console.log(newCar)  // {model: "Fiat", year: 2006, miles: 200 100 }

This part is totally fine but let’s go and print the original object.

console.log(car)  // {model: "Fiat", year: 2006, miles: 200 100 }

So, modifying the copy object using = affected the original object also. This happens because objects are reference types. What means reference types? The reference type means that every value that is stored in the original or the copy of the object is pointing to the same object.

But, this is not the scenario we like to have. When storing the object into a copy we should be able to modify only the copy properties not the properties from the original object.

Let’s dive into the methods of how to clone an object and change its properties without changing anything in the original.


Clone object in JavaScript using the Spread operator

Introduced in ES6 the spread operator ... can spread properties into an object.


const car = {
  model: "Fiat",
  year: 2006,
  miles: 200 000
}

let newCar = [ ...car }

console.log(newCar) // {model: "Fiat", year: 2006, miles: 200 000 }

Making a copy of the object using the spread operator does not make reference and because of that changes on the copy object won’t affect the original one.


let newCar = [ ...car }

newCar.miles = 200 100

console.log(newCar) // {model: "Fiat", year: 2006, miles: 200 100 }

console.log(car) // {model: "Fiat", year: 2006, miles: 200 000 }

The spread operator creates a shallow copy of the object.

Clone object in JavaScript using the Object.assign()

Object.assign() is one alternative to the spread operator. We are able to use this method to copy from single or multiple objects to the target object.


let newCar = Object.assign({}, car)

newCar.miles = 200 100

console.log(newCar) // {model: "Fiat", year: 2006, miles: 200 100 }

console.log(car) // {model: "Fiat", year: 2006, miles: 200 000 }

Object.assign() method also does not create reference, so changes from the copy object won’t affect the original one.

The Object.assign() method creates a shallow copy of the object.

Clone object in JavaScript using the JSON.parse()

JSON.parse() should be used together with JSON.stringify().

This method can be used to create a deep copy.


const car = {
  model: "Fiat",
  year: 2006,
  miles: 200 000
}

let newCar = JSON.parse(JSON.stringify(car));
newCar.miles = 200 100

console.log(newCar) // {model: "Fiat", year: 2006, miles: 200 100 }
console.log(car) // {model: "Fiat", year: 2006, miles: 200 000 }

And, same as the other 2 methods we mentioned for coping an object JSON.parse() does not create reference and changes will not affect the original object.

JSON.parse() will create deep cloning. This method may have its downsides since it will not work with function or symbol properties.

Conclusion

In conclusion, in order to copy object in JavaScript is a crucial operation that offers various benefits.

By employing techniques like shallow and deep copying, we can preserve data integrity, ensure immutability, achieve reference independence, modify complex structures, and facilitate comparison and testing.

Understanding these techniques empowers developers to work with objects effectively while maintaining control over data manipulation and minimizing unintended side effects.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Looking For Something?

Follow Us

Related Articles

How to Open Links in a New Tab Using HTML and JavaScript

How to Open Links in a New Tab Using HTML and JavaScript

Introduction How to Open Links in a New Tab Using HTML and JavaScript Have you ever clicked on a link and wished it would open in a new tab instead of navigating away from the current page? Well, you're in luck! In this blog post, we'll guide you through the simple...

Recursion in JavaScript: Why and How

Recursion in JavaScript: Why and How

Recursion is a powerful programming concept that often mystifies beginners, but it's an essential tool in a developer's toolkit. In JavaScript, recursion involves a function calling itself to solve a problem. This might sound a bit perplexing at first, but let's break...

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!