Nanfeng

Notes on software development, code, and curious ideas

TypeScript Object Assignment and Equality: References, Shallow and Deep Copy

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
2
3
4
5
let a = { value: 1 };
let b = a;
console.log(a === b); // true
b.value = 3;
console.log(a.value); // 3

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
2
import _ from 'lodash';
const copy = _.cloneDeep(original);

Two separate objects with identical properties are not equal under === because their references differ:

1
2
3
4
const a = { x: 1 };
const b = { x: 1 };
console.log(a === b); // false
console.log(_.isEqual(a, b)); // true

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.

+