DEV Community

Utsav Ladani
Utsav Ladani

Posted on

3 1

Difference between Object.assign() and just assign

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
utsavladani profile image
Utsav Ladani • 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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay