In this video, you saved tonight’s game queue for an undo and found that a second name doesn’t make a copy. Here are the key points:
- A name is an arrow to its array or object.
const saved = queue;copies the arrow, not the array, so both names point at one array. - A change through one name shows through every name. After
queue.push("Carcassonne"),savedshows four games too. - Make a real copy when you need a separate one.
queue.slice()with no arguments copies the whole array, and[...queue]makes the same copy. constfixes where the arrow points, not what’s in the array. That’s whypush()works on aconstarray, and whyqueue = saved;throwsTypeError: Assignment to constant variable.Declare the name withletto point it somewhere else. Afterward, both names share one array again, so copy the queue into a new name before the next change.- A function’s parameter gets a copy of the arrow, so a function can change the caller’s array or record. Choose on purpose whether to change the record or to copy it with
{ ...player }and return the new one. - These copies are one level deep. A copy of
playersgets new slots, with arrows to the same records, so changing a record through the copy changes it forplayerstoo.withFriendis still safe, because it copies the record itself, and a record’s fields here are plain values.
Here’s the copy that keeps the saved queue separate, and the undo that points the queue back at it. At the end of main.js, replace the last lesson’s queue experiment with these lines, so queue is declared only once:
let queue = ["Azul", "Catan", "Codenames"];
const saved = queue.slice();
queue.push("Carcassonne");
console.log("Saved:", saved);
console.log("Queue:", queue);
queue = saved;
console.log("Queue:", queue);
Save, and the Console shows the saved copy, the queue with Carcassonne, and the queue back at three games: