1

I'm doing an online bootcamp and just run accross the following info about the spread operator:

Here's how to copy an object into a completely separate object, using the spread operator.

const car1 = {
    speed: 200,
    color: 'yellow'
}
const car 2 = {...car1}

car1.speed = 201

console.log(car1.speed, car2.speed)

Why would I choose to do that instead of just doing

const car2 = car1
  • 2
    `const car2 = car1` doesn't make a copy of the object. It sets both variables to point to the same object. – Andy Ray Oct 13 '22 at 04:24
  • 1
    See also [this question](https://stackoverflow.com/q/73883002/438273) and the [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) algorithm. – jsejcksn Oct 13 '22 at 04:26
  • Pay close attention to the fact that the spread operator makes a **shallow** copy. That said, have a look at the `structuredClone` link in the comment above, which makes a deep copy. – Gerardo Furtado Oct 13 '22 at 04:27
  • 1
    "_copy an object into a completely separate object_" is a non-technical description. Does this answer your question? [How to clone ES6 import data to make independently mutable objects?](https://stackoverflow.com/questions/73883002/how-to-clone-es6-import-data-to-make-independently-mutable-objects) – jsejcksn Oct 13 '22 at 04:34

2 Answers2

1

All primitive datatypes are copied with direct assignment operator, whereas non-primitive datatypes just assigns the reference. Object and Array are non-primitive datatypes in JavaScript.

const car1 = {
    speed: 200,
    color: 'yellow'
}
const car2 = car1; // This does not copy car1 to car2, instead assigns only the reference

console.log(car1 == car2); // true

car2.speed = 300; // Changing car2 also changes car1

console.log(car1.speed); // 300
console.log(car2.speed); // 300

With spread operator, non-primitive datatypes can be shallow copied.

const car1 = {
    speed: 200,
    color: 'yellow'
}
const car2 = { ...car1 }; // Shallow copy
const car3 = Object.assign({}, car1); // Using Object.assign

console.log(car1 == car2); // false
console.log(car1 == car3); // false

car2.speed = 300;
car3.speed = 400;

console.log(car1.speed); // 200
console.log(car2.speed); // 300
console.log(car3.speed); // 400

Similarly, Arrays can be shallow copied as below.

const fruits1 = ['apple', 'orange'];
const fruits2 = [ ...fruits1 ];
const fruits3 = fruits1.slice();
const fruits4 = [].concat(fruits1);
Wazeed
  • 1,230
  • 1
  • 8
  • 9
1

obj1 = obj2

Above code when mutating obj1 will also mutate obj2, this has caused many problems to me before.

If you want to mutate only obj1, then do the spread operator on {...obj2}, it's basically cloning the obj2 into obj1

See here: https://www.javascripttutorial.net/es-next/javascript-object-spread/

idiglove
  • 325
  • 3
  • 10