Tag Archive for: Shallow copy

Copying objects

JavaScript is always pass by value, except when you are working with object that is pass by reference. In JS objects are not like in other languages. An object is a collection of properties, for example an array is an object too.

So, how do we copy objects straightforward? There are 2 basic options depending of the object depth.

A) Shallow copy where all nested objects are still copied as reference, so any change in those nested objects in obj_B will change obj_A.

const obj_B  = {...obj_A}
const arr_B  = [...arr_A]

B) Deep copy where the two objects will be completely different even with nested objects.

const obj_B  = JSON.parse(JSON.stringify(obj_A))

To know more check MDN Web Docs.