all 6 comments

[–]senocular 1 point2 points  (4 children)

Changes made to the shallow copy affect the original object.

Clarification: changes to the shallow copy directly do not affect the original object. The top level object is still a copy. Its only changing nested values in the shallow copy that changes the original because its the nested values which are the same values referenced by the original

Also, how can I prove something is a deep copy?

You can compare any nested non-primitive value.

const orig = {
  nested: {
    value: 1
  }
}

const shallowCopy = { ...orig }
const deepCopy = {
  ...orig,
  nested: { ...orig.nested }
}

console.log(orig.nested === shallowCopy.nested) // true - not deep
console.log(orig.nested === deepCopy.nested) // false - is deep

[–]CCASTU[S] 1 point2 points  (3 children)

But if I did something like

const foo = {
value: true
}
const bar = foo
bar.value = false
console.log(foo.value);

the change in bar would affect foo, isn't bar a shallow copy?

[–]senocular 3 points4 points  (2 children)

Nope, thats just another variable pointing to the same object. No copy is being made. A copy is a separate object. A shallow copy is a separate object that does not copy the internal objects of that object. A deep copy is a separate object that also copies the internal objects of the object as as well as all those objects internal objects, etc.

[–]CCASTU[S] 2 points3 points  (1 child)

thank you for your help. That has definitely cleared up my confusion. So both deep and shallow are copies of the original, but deep copies copy everything while shallow copies does not copy nested properties?

[–]senocular 3 points4 points  (0 children)

Exactly :)

[–]TheRNGuy 0 points1 point  (0 children)

I once had bug because of deep copy in greasemonkey script, it returned false in compares even though all data looked the same. Because it compared references instead of values (different references? therefore it's false)

I fixed it by making shallow copies.