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.
Instagram ● Twitter ● Facebook
Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript
codedrops.tech
Top comments (1)
Oh yes, I forgot to mention its
shallow cloning
. I have a post on Deep cloning too.Thanks