Copying vs Referencing
The full text of this chapter, to read or revisit. To practise, do the exercises.
βΆ Do the exercisesExercise 1 β Two Names, One Array
Imagine you want to save a backup of your current team before testing a new lineup. You might try writing `const backup = team`. Watch out: in JavaScript, assigning an array to another variable does not create a separate copy!
const team = ["Aquachu", "Zap"];
const backup = team;
backup.push("Pyrochu");
console.log(team);
console.log(backup);You only pushed `"Pyrochu"` into `backup`, yet `team` was modified too! That's because both variables point to the exact same array in memory β they are just two labels for the same data.
Exercise 2 β Values vs References
Why didn't that happen earlier with numbers, strings, or booleans? Because primitive values (`number`, `string`, `boolean`) are copied by value: each variable holds its own independent copy. Changing one never affects the other:
let levelA = 5;
let levelB = levelA;
levelB = 99;
console.log(levelA);
console.log(levelB);Arrays and objects work differently: they are stored by reference. A variable doesn't hold the object itself, but the memory address where it lives β so copying the variable only copies that address.
Exercise 3 β Quiz: Shared or Copied?
What does this code print?
const a = { hp: 40 };
const b = a;
b.hp = 10;
console.log(a.hp);1040undefinedHint : Ask yourself how many objects exist in memory here.
Exercise 4 β Making a Real Copy
The spread operator is the everyday fix. It builds a new array or object, so the two are independent:
const team = ["Aquachu", "Zap"];
const backup = [...team];
backup.push("Metachu");
console.log(team.length);
console.log(backup.length);Same idea with objects:
const zap = { name: "Zap", hp: 45 };
const copy = { ...zap };
copy.hp = 10;
console.log(zap.hp);
console.log(copy.hp);Exercise 5 β Quiz: Protected by the Spread
What does this code print?
const a = [1, 2];
const b = [...a];
b[0] = 99;
console.log(a[0]);1992undefinedHint : The spread built something new before the change happened.
Exercise 6 β The Copy Is Only Skin Deep
Careful: the spread copies one level only. If a property holds another object, that inner object is still shared:
const trainer = {
name: "Sam",
starter: { name: "Aquachu", hp: 40 }
};
const copy = { ...trainer };
copy.starter.hp = 10;
console.log(trainer.starter.hp);The outer objects are separate, but both `starter` properties point at the same inner object. This is called a shallow copy.
To protect the inner object too, spread it as well:
const trainer = {
name: "Sam",
starter: { name: "Aquachu", hp: 40 }
};
const copy = { ...trainer, starter: { ...trainer.starter } };
copy.starter.hp = 10;
console.log(trainer.starter.hp);
console.log(copy.starter.hp);Exercise 7 β Quiz: Deep Enough?
What does this code print?
const a = { stats: { hp: 50 } };
const b = { ...a };
b.stats.hp = 5;
console.log(a.stats.hp);550undefinedHint : How many levels down does a spread actually reach?
Exercise 8 β Protect the Original
Build `backup` so that pushing into it leaves `team` untouched.
Hint : One symbol builds a separate array, and the element goes at the end.
Exercise 9 β Copy Cheat Sheet
Match each line with its effect.
const b = a (numbers)const b = a (arrays)const b = [...a]const b = { ...a } (nested)Exercise 10 β Safe Save Slot
Before a risky battle, the game saves the trainer's state. The save must survive whatever happens next.
Step 1: build `save`, a copy of `trainer` where the `team` array and the `starter` object are also copied, not shared. Step 2: the battle goes badly. In `trainer`, add `"Rockachu"` to the team and drop the starter's HP to 0. Step 3: print the current state, then the saved state, in the format shown below.
Expected output:
Now: 3 members, starter at 0 HP
Save: 2 members, starter at 40 HPconst trainer = {
name: "Sam",
team: ["Aquachu", "Zap"],
starter: { name: "Aquachu", hp: 40 }
};
// Write your code here