A shallow copy duplicates only the top-level container. Nested objects and arrays remain shared between the original and the copy; this shared structure is called structural sharing. section 6.13 section 6.14
Use a shallow copy as the foundation of copy-on-write:
- Make a shallow copy of the container you need to change. section 6.14
- Modify the copy rather than the original. section 6.20
- Return the copy, preserving the original value. section 6.20
Updating a shopping cart
To change one item's price, copy the cart with `cart.slice()`, copy the matching item with `Object.assign({}, item)`, change that item copy, replace it in the copied cart, and return the cart copy. Only the array and changed item need copying; unchanged items remain structurally shared. section 6.17 section 6.18
Shallow copying is relatively cheap because unchanged nested data is reused. It is safe when shared values remain immutable; use deep defensive copies instead when data crosses into code that may mutate it. section 6.14 section 7.8
Visualize how the original and copied containers point to the same unchanged nested values. section 6.13
