How to Clone Objects in JavaScript
In this tutorial, we will learn how to Clone Objects in JavaScript.
So, let's see how we can do this:
In JavaScript objects are reference values, so we can't simply just copy using the =(equal) operator.
First of all, let see what happens when we clone object using the =(equal) operator
const obj = { user1: 1, user2: 2 }; const obj2 = obj; console.log( obj, // {one: 1, two: 2}; obj2, // {one: 1, two: 2}; );
Now let's update the second object
const obj2.user3= 3; console.log(obj2); // {user1: 1, user2: 2, user3: 3}; <-- ✅ console.log(obj); // {user1: 1, user2: 2, user3: 3};
You will see both objects gets the same value even we didn't update the first object. so why this happens?
It Happens 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.
Now let's see how to clone object without reference type:
1.Clone using Spread Operator:
const user1 = { firstName: 'john', lastName: 'doe' }; const user2 = {...user1}; console.log(user2); //{firstName: "john", lastName: "doe"}
This will be a shallow copy means the first level is copied, deeper levels are referenced.
2.Clone Using Object.assign
const user1 = { firstName: 'john', lastName: 'doe' }; const user2 = Object.assign({}, user1); console.log(user2); //{firstName: "john", lastName: "doe"}
The empty {}
as the first argument, this will ensure you don't mutate the original object
3.Clone Using JSON
const user1 = { firstName: 'john', lastName: 'doe' }; const user2 = JSON.parse(JSON.stringify(user1)); console.log(user2); //{firstName: "john", lastName: "doe"}
Note: This will be a Deep copy