As a newbie I saw that some developer use Object.assign()
for assign a value to object, and some developer use just assign
.
What is the difference between that?
Object.assign()
is clone the object.
Just assign
assign the address.
Here I give you an simple example
let x = { "a":10, "b":100 }
let y = x;
y.a = 50;
console.log(x);
// {a: 50, b: 100}
Here you can see that if we change the value of y.a
then x.a
changes automatically, means x
and y
have same address.
Now for just assign
let x = { "a":10, "b":100 }
let z = {};
Object.assign(z,x);
z.a= 1000;
console.log(x);
// {a: 10, b: 100}
Here you can notice that we change the value of z.a
but x.a
remains as it is, means z
and x
have different address.
In short, Object.assign()
is copy the key-value pair ans just assign
assign the same address.
Here Link for more better understanding.
Here is a useful link for javascript reference.
Javascript.info
Bye bye 2020. π
Top comments (1)
Here
Object.assign()
copy the value of first level's key-value pair, but if your key-value pair's value is object then it will assign by address.Here is example.
Remember this for better understanding.