Middle+
How to copy objects in JavaScript? What types of copying are there?
sobes.tech AI
Answer from AI
In JavaScript, there are two main types of object copying:
-
Shallow copy — copies only the top level of the object, nested objects remain references to the original.
-
Deep copy — creates a complete copy of the object with all nested structures.
Examples:
// Shallow copy using Object.assign
const obj = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, obj);
// Modifying the nested object will affect the original
shallowCopy.b.c = 3;
console.log(obj.b.c); // 3
// Deep copy using JSON
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 4;
console.log(obj.b.c); // 3
For deep copying, you can use libraries (lodash _.cloneDeep) or recursive functions, as the JSON method does not work with functions, dates, and other complex types.