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"]
// 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 tested
// 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?

🤓 The physical therapist who writes JavaScript 💪 Web Developer 😎 Mentor 🧠 DPT 😄 SEO Expert 😁 React 😆 Jamstack 💬 Ask me anything 👉 DoctorDerek.com 👈

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store