Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/22d95e4c4edd580173738fe9a4290972 to your computer and use it in GitHub Desktop.
Save DoctorDerek/22d95e4c4edd580173738fe9a4290972 to your computer and use it in GitHub Desktop.
Shallow copies aren't enough in JavaScript https://medium.com/p/58fa3de25130
// Start with a deeply nested array object:
const array = [37, {a: "b"}, {b: {c: "d"}}]
// Make a shallow copy with Array.from():
const copy = Array.from(array)
console.table(array) // [37, {a: "b"}, {b: {c: "d"}}]
copy[0] = -0 // Change a primitive value (not nested)
copy[1].a = "y" // Change a deeply nested value
copy[2].b.c = "z" // Change another deeply nested value
// Deeply nested objects weren't actually copied:
console.table(array) // [37, {a: "y"}, {b: {c: "z"}}]
// Note how the changes to copy also affected array:
console.table(copy) // [-0, {a: "y"}, {b: {c: "z"}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment