This page looks best with JavaScript enabled

Object Assign Method in Javascript

 ·   ·  ☕ 1 min read

assign method of an object allows us to merge two objects quickly.

1
2
3
4
5
const name = { name: "earth" };
const position = { position: 3 };

const planets = Object.assign(name, position);
console.log("planets: ", planets); // { name: 'earth', position: 3 }

You can also use Object.assign to quickly copy objects.

1
2
3
4
5
6
7
const third = { name: "earth", position: 3 };
const livePlanet = Object.assign({}, third);
console.log("livePlanet: ", livePlanet);

third.position = 3.14;
console.log("third: ", third); // { name: 'earth', position: 3.14 }
console.log("livePlanet: ", livePlanet); // { name: 'earth', position: 3 }

If you do not provide the empty object to assign, only a reference is copied and not the object itself.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things