loading...

Clone an object or array (Shallow Cloning)

318097 profile image Mehul Lakhanpal Originally published at codedrops.tech ・1 min read

Note: This method is for shallow cloning.

const obj = {
  name: 'xyz',
  age: 20
};

const objCopy = obj; // objCopy would still point to the same object.
// i.e., If obj.age is changed (obj.age = 35;),  
// objCopy.age will also be 35

// To clone the object,
// Solution 1 - Use the spread operator. 
const objCopy = {...obj};

// Solution 2 - Object.assign() 
const objCopy = Object.assign({}, obj);

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Discussion

pic
Editor guide
Collapse
318097 profile image
Mehul Lakhanpal Author

Oh yes, I forgot to mention its shallow cloning. I have a post on Deep cloning too.
Thanks