01/04
Shallow Copy
and Deep Copy
in Angular (and
JavaScript)
SWIPE
Shallow Copy:
A shallow copy replicates an object's top-level
properties, but nested objects or arrays remain
references to the original.
Deep Copy:
A deep copy creates a complete independent
clone of the original object, including nested
objects.
Key Notes on Shallow and Deep Copy:
Shallow Copy Methods:
Object.assign({}, obj)
Spread operator (...).
Array slice() or concat(): Creates shallow
copies of arrays.
Deep Copy Methods:
JSON.parse(JSON.stringify(obj) (caveat: does not copy
functions or special objects like Date or RegExp).
Using libraries like lodash (_.cloneDeep).
Writing custom recursive copy functions.
Custom Recursive Functions: Implement custom
functions to recursively copy nested structures,
ensuring deep copies with more control over edge
cases.
If you're working with Angular and want to copobjects
safely, be cautious of the method you choose
depending on your data structure.