0

Edit : Question marked as duplicate, but the duplicated post is not helping me fixing this issue. How can I modify the value of the map2 without changing the one from map1 ? ( Is JavaScript a pass-by-reference or pass-by-value language? )

I have 2 maps. The first one can be considered as a "Source of truth" that is initialized at loading of the page. I want to duplicate the content of the first map into a second one. So all my changes will be applied to the second map, and I will use my first one if I want to revert my changes.

But duplicating a map is the cause of a weird bug that change the content of the first map when the second one is changed.

var map1 = new Map()
var map2 = new Map()

map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
    
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment 
    
var x = map2.get('2')
x.alpha = "why???"
x.beta = "how???"
//Why does the value of the map change when I edit the 'x' variable ?
// map2.set('2', x); is not required ?

console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))

But the snippet blow work well and won't modify the value of the first map (but I can't modify only a part of the content inside map2 with this method)

var map1 = new Map()
var map2 = new Map()

map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
    
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment 
    
map2.set('2', {alpha:'but this', beta:'work ???'})

console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))

What is happening ?

Tryall
  • 640
  • 12
  • 22
  • 1
    the duplicate question answers why the second is working and the first is not. to get independent values, you could stringify the value and get a parsed value back ([`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON)). this approach does not work for custom instances. – Nina Scholz Feb 19 '21 at 19:43
  • it would be easy to give a helping answer like to make a one level 'deep' copy of the map via spread-operator. – Turo Feb 20 '21 at 17:26
  • @Turo Nina scholz hopefully answered my question with the "JSON.parse(JSON.stringify())" method. But yea, stackoverflow is annoying sometimes. – Tryall Feb 21 '21 at 13:32

1 Answers1

1

Because the key 2 contains an object. When creating a new map , it duplicates the object reference and doesn’t really create a deep copy. The only thing that is duplicated is the reference to address where this object is. The other values are primitives , that are deeply duplicated by default