Immutable Data Patterns
Copying Objects
Build a new object from existing fields.
copy-object
Object spread copies fields into a new object. Later fields can add new values without mutating the original shape.
Copying Objects
copy_object.js
Replay: real traced execution (multi-file project)
const quantity = 3;
const copied = JSON.stringify({
...{ item: "book" },
quantity: quantity,
});
const label = "quantity=" + quantity;
console.log("copied=" + copied);
console.log("label=" + label);
const quantity = 5;
const copied = JSON.stringify({
...{ item: "book" },
quantity: quantity,
});
const label = "quantity=" + quantity;
console.log("copied=" + copied);
console.log("label=" + label);
const quantity = 9;
const copied = JSON.stringify({
...{ item: "book" },
quantity: quantity,
});
const label = "quantity=" + quantity;
console.log("copied=" + copied);
console.log("label=" + label);
quantity ← 3, copied ← {"item":"book","quantity":3}, label ← quantity=3
1const quantity→ 3 = 3; //@quantity=5, 92const copied→ {"item":"book","quantity":3} = JSON.stringify({3 ...{ item: "book" },4 quantity: quantity3,5});6const label→ quantity=3 = "quantity=" + quantity3;78console.log("copied=" + copied{"item":"book","quantity":3});9console.log("label=" + labelquantity=3);outputcopied={"item":"book","quantity":3} label=quantity=3
quantity ← 5, copied ← {"item":"book","quantity":5}, label ← quantity=5
1const quantity→ 5 = 5;2const copied→ {"item":"book","quantity":5} = JSON.stringify({3 ...{ item: "book" },4 quantity: quantity5,5});6const label→ quantity=5 = "quantity=" + quantity5;78console.log("copied=" + copied{"item":"book","quantity":5});9console.log("label=" + labelquantity=5);outputcopied={"item":"book","quantity":5} label=quantity=5
quantity ← 9, copied ← {"item":"book","quantity":9}, label ← quantity=9
1const quantity→ 9 = 9;2const copied→ {"item":"book","quantity":9} = JSON.stringify({3 ...{ item: "book" },4 quantity: quantity9,5});6const label→ quantity=9 = "quantity=" + quantity9;78console.log("copied=" + copied{"item":"book","quantity":9});9console.log("label=" + labelquantity=9);outputcopied={"item":"book","quantity":9} label=quantity=9