0

I have this code:

let a = {x: "x"};
let b = {b: "b"};

let versions = [a, b];
let copyOfVersions = Array.from(versions);
let test = ["test"];
    
copyOfVersions[0].versions = Array.from(test);

console.log(versions[0].versions);

How come that versions table values have changed too?

Thanks!

Anna
  • 839
  • 2
  • 17
  • 33
  • 3
    Array.from does not perform deep copy – juvian Jun 22 '17 at 14:50
  • 2
    Why do you think that `Array.from` _copies the objects_ in the array? – Sebastian Simon Jun 22 '17 at 14:50
  • I used `Array.from` when I found this post [Copying array by value in JavaScript](https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript). But even if doesn't perform a copy, it creates a new instance. So I don't understand why the original value changes? – Anna Jun 22 '17 at 14:54
  • 1
    Possible duplicate of [Javascript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – Matus Jun 22 '17 at 14:55
  • Quoting your link on accepted answer : "slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays." – juvian Jun 22 '17 at 14:55

2 Answers2

1

Yes, you created a new instance of an array by using Array.from. So versions and copyOfVersions are two different objects, but they both contain list of references to the same objects. So that means when you say copyOfVersions[0] and versions[0] you are basically accessing the same object a. Then when you use .versions you are adding a new field. In the end, only object a has been changed and that's what you see as print out.

vojislavdjukic
  • 428
  • 2
  • 8
1

a and b are references to the objects {x: "x"} and {b: "b"} respectively.

When you create a new array, those references are copied to the new array but the referenced objects are NOT copied, it's still the original objects that are referenced.

copyOfVersions[0] gets the referenced object, the same object referenced by versions[0], and then you create the property versions on that object. Since the object itself was never copied, you're modifying the original object.

Lennholm
  • 7,205
  • 1
  • 21
  • 30