Hey Jeremy, thanks for reading and responding! The definition of shallow copy you cite is usually not referred to as a “copy” — because nothing got copied. If you have an array in x, and you assign it to y, it’s the same array (the same reference in memory). That’s what you quoted as being a “shallow copy” — but there was no copy.
When you copy something, you’re implying a new reference in memory. Where it gets a little complicated is that JavaScript primitive types are immutable, meaning they can’t be changed. Typically, we don’t refer to these as having memory references, since we’re talking about “object references in memory” by that phrase.
So if you have an array of all primitive types, you can copy it with Array.from or the spread operator. But if that array contains other objects or arrays, the nested object references will be copied. The result is that for a shallow copy, you could modify the nested objects in the copy by changing those objects in the original array.
Here’s an example:
const inner = [3]
const x = [inner,"Hi"] // nested array
const y = x // not a copy
const shallow = Array.from(x) // shallow copy
const deep = [Array.from(inner),"Hi"]console.log(`[${x}]...[${y}]...[${shallow}]...[${deep}]`)
// Output: [3,Hi]...[3,Hi]...[3,Hi]...[3,Hi]x[0][0] = 7 // change the nested value of inner
x[1] = "Bye" // change the value that's not testedconsole.log(`[${x}]...[${y}]...[${shallow}]...[${deep}]`)
// Output: [7,Bye]...[7,Bye]...[7,Hi]...[3,Hi]
Since JavaScript arrays can contain different types, I used a nested array containing a number and compared it to a string.
Hopefully, you can see that array y is never a copy of x, since they will always be exactly identical — it’s the exact same variable (object reference to the array object) in both.
Does that answer your question?