#100DaysOfCode Day 17: Object.assign

Shawn McMahon
2 min readJul 29, 2021

Day 17: Object.assign

Today I want to do some self-learning on Object.assign. So let’s get into it.

Writers block
Source : https://www.pexels.com/photo/person-with-difficulty-and-questions-in-studies-5428833/

Object.assign

Object.assign is similar to object.keys and object.values. One key difference for Object.assign outputs an object instead of an array. Another difference is that it takes in 2 objects instead of 1; one target and one source (example: Object.assign({target}, {source}). The method will combine both objects into one object. Okay sweet!

What about similar keys?

So what happens when each of those objects contains the same key? Object.assign will overwrite the property in the target object with the key in the source object.

Consider the example below. There is a target object with two keys (a = 1 and b = 2). And there is a source object with two keys (b = 4 and c = 5). When we put these objects as arguments inside Object.assign the source object will override the target object. This will return the target object that has been changed.

Anything else?

It’s important to note one more thing. Object.assign does not just return a new object. It returns the target object. This means that the target object is changed forever. If you need the target object to stay unchanged somewhere else in your program, you may want to create a new variable with this object so your original object stays intact.

--

--