Why b = a Does Not Copy an Array
Look at this code. What do you expect it to print?
const a = [120, 95, 42];
const b = a;
b.push(4);
console.log(a);
console.log(b);
Output:
[ 120, 95, 42, 4 ]
[ 120, 95, 42, 4 ]
You added 4 to b, but a changed too. The reason is that a variable does not hold the array itself. It holds a reference, which works like an arrow pointing to the array in memory. const b = a copies the arrow, not the array:
a ----+
+----> [120, 95, 42, 4]
b ----+
There is only one array, with two names pointing to it. So a change made through b is also seen through a.
Numbers, strings and booleans do not work like this. They are called primitive values, and assigning one copies the value itself:
let x = 5;
let y = x;
y = y + 1;
console.log(x, y);
Output:
5 6
References also explain how === works on arrays. It compares the arrows, not the elements. Two arrays that you build separately are two different arrays, even when they hold the same elements:
console.log([1, 2, 3] === [1, 2, 3]);
const c = [1, 2, 3];
const d = c;
console.log(c === d);
Output:
false
true
And it explains why const did not stop temps[1] = 22 in the Array Basics lesson. const fixes the arrow, so the name always points to the same array. The array itself can still change.
To get a real copy, use spread or slice():
const prices = [7, 3, 5];
const copy = [...prices];
prices[0] = 9;
console.log(prices);
console.log(copy);
Output:
[ 9, 3, 5 ]
[ 7, 3, 5 ]
Now there are two separate arrays, so the change to prices stays in prices. prices.slice() makes the same kind of copy.
These copies have one limit. They copy only the top level of the array, so they are called shallow copies. If the elements are arrays themselves, the copy still points to the same inner arrays. For a full copy of nested data, use structuredClone:
const grid = [[1, 2], [3, 4]];
const shallow = [...grid];
const deep = structuredClone(grid);
grid[0].push(99);
console.log(shallow[0]);
console.log(deep[0]);
Output:
[ 1, 2, 99 ]
[ 1, 2 ]
This is the real reason the earlier lessons prefer slice, spread and toSorted. When code builds new arrays instead of changing shared ones, a change in one place cannot quietly break another.
In the exercise, Alice's backup of her sales changes when the sales change. Fix the copy with spread.