Glossary / Shallow copy
Shallow copy
A shallow copy creates a new outer array or object while keeping references to nested values. It isolates top-level assignment and deletion but does not recursively duplicate the object graph. Object spread, Object.assign, array spread, slice, and Array.from commonly create shallow copies.
Aliasing example
const original = { profile: { name: "Ada" } };
const copy = { ...original };
copy.profile.name = "Grace";
console.log(original.profile.name); // "Grace": nested object is shared
Object spread copies enumerable own string and Symbol properties and reads their values; getters can execute. It does not preserve the prototype, property descriptors, or non-enumerable fields. Array spread copies element references and densifies holes as undefined values. These operations are often appropriate for immutable state updates when every changed level is copied and unchanged subtrees are intentionally shared.
A shallow copy is not isolation from untrusted callers when nested values remain mutable. Document whether an API accepts or returns shared references. Use a targeted nested copy or immutable/persistent data model where ownership needs stronger separation.
Interview questions
- What is copied? The outer container and its immediate property/element values.
- Are nested objects independent? No, references are shared.
- Does object spread preserve descriptors/prototype? No.
- When is shallow copy useful? Immutable updates that copy only changed levels and intentionally share unchanged data.