3 Different ways to Copy Objects in Javascript





Hey guys in this post we will discuss the different ways of copying objects in javascript. There 3 different ways that we can copy javascript objects let’s discuss them one by one

Three Different ways


To copy an object in javascript, we have three options:

  • spread()
  • Object.assign()
  • JSON.stringify() and JSON.parse()

Why can’t i use = ?


So our first question that comes to our mind is, why can’t we use = ?. Let’s see what happens if we do that

const obj = {one: 1, two: 2};

const obj2 = obj;

console.log(obj, obj2);
//{one: 1, two: 2}
//{one: 1, two: 2}

So far, both object seems to output the same thing. so no problem, right? But let’s see what happens if we edit out the second object:

obj2.three = 3;

console.log(obj, obj2)
//{one: 1, two: 2, three: 3}
//{one: 1, two: 2, three: 3}

So if you changed obj2 then obj also affected. That’s because objects are reference types. So when you use =, it copied the pointer to the memory space it occupies. Reference types don’t hold values, they are a  pointer to the value in memory.

Using spread()


Let’s see an example of how we can copy an object using spread()

const employee = {name: 'Bushan', age: 27};

const copyEmployee = {...employee};

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27}

Now let’s see what will happen if we make changes to our employee object.

employee.location = "India";

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27, location: "India"}

Using Object.assign()


Let’s see an example of how we can copy object using Object.assign()

const employee = {name: 'Bushan', age: 27};

const copyEmployee = Object.assign({}, employee);

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27}

Now, let’s see what will happen we make changes to our employee object

employee.location = "India";

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27, location: "India"}

Using JSON.stringify() and JSON.parse()


Let’s see an example of how we can copy objects using JSON.stringify() and JSON.parse()

const employee = {name: 'Bushan', age: 27};

const copyEmployee = JSON.parse(JSON.stringify(employee));

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27}

Now, let’s see what will happen we make changes to our employee object

employee.location = "India";

console.log(copyEmployee, employee);
//{name: "Bushan", age: 27}
//{name: "Bushan", age: 27, location: "India"}




About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

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