Copying Arrays and Objects in JavaScript
1. Shallow Copy For Objects
1.1 Object.assign() for Shallow Copy:
let person = { name: "Max", hobbies: ["sports", "cooking"] };
let secondPerson = Object.assign({}, person);
person.name = "Chris";
person.hobbies.push("reading");
console.log(secondPerson); // Output: { name: "Max", hobbies: ["sports", "cooking", "reading"] }1.2 Object.create() for Shallow Copy:
let person = { name: "Max", hobbies: ["sports", "cooking"] };
let secondPerson = Object.create(
Object.getPrototypeOf(person),
Object.getOwnPropertyDescriptors(person)
);
// Making modifications to the original object
person.name = "Chris";
person.hobbies.push("reading");
console.log(secondPerson);
// Output: { name: "Max", hobbies: ["sports", "cooking", "reading"] }1.3 Spread Operator for Shallow Copy
2. Deep Clone For Objects
2.1 Using JSON.stringify() for Deep Cloning
2.2 Using structuredClone() for Deep Cloning
3. Copy For Array
Summary
For Objects:
Method
Advantages
Limitations
For Arrays:
Method
Advantages
Limitations
List of References
Last updated