Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign vs assignment (=)

I am trying to make an instance of an object. I got a little confused facing Object.assign(). What's the difference between the below 2 codes?

const obj3 = Object.assign(obj2, obj1);

and:

let obj2: model;
obj2= obj1;
like image 709
Qiimiia Avatar asked Mar 22 '26 09:03

Qiimiia


1 Answers

Assignment only creates another reference to the exact same object in memory. If you assign, then change by referencing one of the variable names, the other one will have changed too, since they're the same thing.

Object.assign will assign all enumerable own properties of the second (and further) parameters to the first parameter, and will return the first parameter. So

const obj3 = Object.assign(obj2, obj1);

is a bit like

for (const prop in obj1) {
  obj2[prop] = obj1[prop]
}
obj3 = obj2;

(with plain objects - skipping the own aspect)

They're quite different.

like image 174
CertainPerformance Avatar answered Mar 23 '26 21:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!