In this video, you gave Dana a what-if budget that’s separate from her real one, all the way down, by copying it with structuredClone().
Key Points
- Every file that imports
budgetshares one object, so a what-if budget needs a copy. Dana tries copies out in a short file,whatif.js, next to her tracker. - Spread copies each top-level property into a new object. The value of
limitsis a reference to an object, so{ ...budget }gets the same reference, and both budgets share onelimitsobject. The same goes forstartsOn: both budgets share one Date. Cutting groceries on the copy changed the real budget in that run too, and each run starts again from the 450 and 150 inbudget.js. That’s a shallow copy. Object.assign({}, budget)copies the properties ofbudgetinto the empty object you give it, and returns that same object. It’s shallow too. Watch out: a new object on the outside doesn’t mean new objects inside.- A deep copy copies every level.
JSON.parse(JSON.stringify(budget))builds brand-new objects from the text, so the real limits stayed at 450 and 150. However, JSON turnedstartsOninto a string, andJSON.parse()has no way to know it was ever a date. - Watch out: a JSON round trip is a safe copy only for data that’s already JSON-shaped, since it also drops
undefinedproperties and turns a Map into an empty object. structuredClone()is a global function that Node and browsers provide. It makes a deep copy and keeps some types JSON can’t hold, such as Dates and Maps. The copy’sstartsOnis no longer a string, and it’s a Date of its own. It can’t copy functions, though, and throws an error instead. Dana’s budget is plain data, so that’s no problem here.- When the copy must be separate all the way down,
structuredClone()is the tool to use.
| Copy tool | What it copies |
|---|---|
{ ...budget }, Object.assign() |
The top level only |
JSON.parse(JSON.stringify()) |
Every level; a Date becomes a string, a Map becomes {}, undefined properties are dropped |
structuredClone() |
Every level; keeps Dates and Maps; throws an error on functions |