0

Today I discovered something that I don't understand so can you explain to me how it works :

let places = [
  { num: 1, name: 'a'},
  { num: 2, name: 'b'},
  { num: 3, name: 'c'},
]

const order = (arr, numOut) => {
  let newArr = new Array(...arr)
  newArr[1].num = numOut;

  console.log(newArr);
}

order(places,3);
console.log(places);

// OUTPUT :
// [ { num: 1, name: 'a' }, { num: 3, name: 'b' }, { num: 3, name: 'c' } ]
// [ { num: 1, name: 'a' }, { num: 3, name: 'b' }, { num: 3, name: 'c' } ]
let places = [
  { num: 1, name: "a" },
  { num: 2, name: "b" },
  { num: 3, name: "c" },
];

const order = (arr) => {
  let newArr = new Array(...arr);
  newArr.push({ num: 4, name: "d" });

  console.log(newArr);
};

order(places);
console.log(places);

// OUTPUT :
// [{ num: 1, name: 'a' },{ num: 2, name: 'b' },{ num: 3, name: 'c' },{ num: 4, name: 'd' }]
//[ { num: 1, name: 'a' }, { num: 2, name: 'b' }, { num: 3, name: 'c' } ]

So why the original array is modified while with the push method only the new one is modified ?

mystr
  • 1
  • The array contains references to objects. No copy is made when you pass the reference into the function. – Pointy Feb 01 '21 at 20:15

1 Answers1

0

In the let newArr = new Array(...arr); line you're creating a shallow copy of the array. In other words, you're having an array of some object references and you are creating a different array of the same object references.

In your example:

  • Array A consists of references to object C, object D and object E.
  • Array B also consists of references to object C, object D and object E (shallow copy).
  • The newArr[1].num = numOut; changes the num value of object D.
  • The push() method is invoked on the array B and adds there a reference to a newly created object F

Read more about shallow and deep copies here: What is the difference between a deep copy and a shallow copy?

Marcin Restel
  • 280
  • 3
  • 13