Home > Back-end >  what's the difference and why would I choose the spread operator
what's the difference and why would I choose the spread operator

Time:10-13

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

CodePudding user response:

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);

CodePudding user response:

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/

  • Related