DEV Community

loading...

Difference between Object.assign() and just assign

Utsav Ladani
Project enthusiastic | Love JavaScript and Open Source | Learner
・1 min read

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}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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. 😄

Discussion (1)

Collapse
utsavladani profile image
Utsav Ladani Author • Edited

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.

let x = { "a":{c:10}, "b":100};
let z = {};
Object.assign(z,x);
z.b = 1000;
z.a.c = 50;
console.log(x);

// {a: {c: 50}, b: 100}
Enter fullscreen mode Exit fullscreen mode

Remember this for better understanding.