2

So I have these few lines of code:

  console.log(...cells);

  let testCells = [...cells];
  testCells[index].shape = selectedShape;
  testCells[index].player = player;

  console.log(...cells);

The interesting thing is that it is console.log()ing back the following.

enter image description here

I don't quite get it, why does cells change? There is no other part of the code that could interfere with cells. Any tips?

Full code available here.

Laczkó Örs
  • 1,082
  • 1
  • 18
  • 38

1 Answers1

1

It looks like even though you're spreading all the objects into the new array, it is still a reference to the old objects. You can break the reference by using JSON.stringify and JSON.parse to avoid any old unintended relationships.

  const cells = [
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
  ];
  
  console.log(...cells);
  
  const breakRef = obj => JSON.parse(JSON.stringify(obj));

  let testCells = breakRef(cells);
  testCells[0].shape = 1;
  testCells[0].player = 0;

  console.log(...cells);
async await
  • 1,967
  • 1
  • 8
  • 19
  • Thanks! I'll try it. Any idea why reference is not broken? – Laczkó Örs Apr 15 '22 at 19:26
  • Just the way objects work in js, when you assign an object to a new variable it works as a reference. Check out [this answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) for more info :) – async await Apr 15 '22 at 19:27
  • 1
    Thank you! I thought that the spread operator should break all references by itself, but I guess it doesn't. You really saved me from a few more hours of debugging! – Laczkó Örs Apr 15 '22 at 19:29