liveBook · Manning

Shallow copy

As explained in Grokking Simplicity

A shallow copy is a copy of a data structure's top-level container that retains references to the nested values rather than copying them recursively.

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

Image

Visualize how the original and copied containers point to the same unchanged nested values. section 6.13

How Grokking Simplicity covers it

How deep it goes
Defines top-level copying, demonstrates nested updates, and contrasts shallow sharing with more expensive deep copying.
Examples
Uses JavaScript arrays, objects, a shopping cart, item prices, quantities, and a mailing list.
What it assumes
Assumes basic JavaScript arrays and objects while defining nested data, structural sharing, and copy-on-write explicitly.
What you can do after
Apply it via JavaScript's slice and Object.assign to update nested data without modifying the original structure.
How it connects
Connects structural sharing, copy-on-write, immutability, deep copy, and defensive copying.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.