Cloning Object
Deep Clone Objects
Deep cloning means nested fields and subfields in an object are given new memory rather than referenced to an old memory.
const original = { a: 1, b: { c: 2, d: { e: 3 } }, }; const clone = JSON.parse(JSON.stringify(original)); clone.b.d.e = 4; original.b.d.e === clone.b.d.e // false
JSON
approach only works for JSON-compatible data types (e.g., no functions
, undefined
, Map
, Set
, or Date
).
Shallow Clone Objects
Shallow clone references the same memory address of nested objects.
- Since
address
is a nested property in an object,shallowClone.address
andoriginal.address
point to the same memory. - Mutating
shallowClone.address
will affectoriginal.address
.
shallow cloning only applies to nested array/objects
const original = { name: "Alice", age: 25, address: { city: "New York", zip: "10001" } }; // Shallow cloning with spread operator const shallowClone = { ...original }; shallowClone === original // false shallowClone.address === original.address // true