Learning object 27 of 100
Shallow versus deep copy explorer
Compare spread copies with structuredClone and watch which nested values are still shared after copying.
Loading…
What it shows
Spread ({ ...obj }, [...arr]) and Object.assign make shallow copies: a new outer object whose nested objects and arrays are still shared. structuredClone copies every level of plain data, so changes to the clone never reach the original.
Guided experiment
- In Shallow copy, step until tags changes. Which object did it change?
- In Deep copy, compare the final line with the shallow version.
- In Copy one level, see how copying only the nested array fixes the problem.
Predict
After const c = { ...o }, is c.list === o.list true when o.list is an array?
Related
Lessons: Lesson 39: Object copying and reference behavior
Projects: Project 9: Shopping Cart Price Calculator
Source: web/assets/js/objects/object-027.js in the companion repository.