Objects and arrays in JavaScript and TypeScript are reference values. Assigning one variable to another with = makes both variables refer to the same object:
1 | let a = { value: 1 }; |
A shallow copy duplicates only the first level. Nested objects remain shared. For a simple serializable object, one deep-copy option is:
1 | const copy = JSON.parse(JSON.stringify(original)); |
This does not preserve functions, dates, special types, or circular references. Modern environments can use structuredClone; Lodash also provides cloneDeep:
1 | import _ from 'lodash'; |
Two separate objects with identical properties are not equal under === because their references differ:
1 | const a = { x: 1 }; |
Class instances can also differ in their prototype chains. Decide whether your operation requires identity comparison, shallow copying, deep copying, or structural equality, and choose the corresponding mechanism explicitly.