The Difference Between Object.create and Object.assign

The major difference between Object.create() and Object.assign() is that the Object.assign method creates a new Object. it uses the object provided as the prototype to the newly created Object. While Object.assign() method copies all the properties from the source objects to the target object which is the first parameter of this function and returns this target Object.

Now Let’s check this knowledge we have with few examples.

Understanding Object.create() .

As we know Object. create method creates a new Object. This new Object uses the Object specified in the create method as the prototype to this new Object. So, the first argument to our object.create() method is the prototype object, every object specified after this method is the property object. Which would define what properties our returned object would have. Take a look at the example provided below.

 var person = {
    name : 'x',
    age : 21,
    gender : 'Male',
    printName : function(){
        console.log(`My name is ${this.name}`)
    }
}
var y = Object.create(person)

Object.create example

As you can see with the above example that our new Object ‘y’ inherited all the properties of the object ‘person’. Now you can also add new properties to any object created with Object.create by passing those properties as the second argument to the Object.create function.

for example:

The second argument in our Object.create() which is an Object of Object where each nested object defines the value of the property is set to our newly created Object.

Understanding Object.assign() .

The Object.assign on the other hand simply copies all the properties from the specified object to the specified target Object and simply returns that new Object.

Now the whole purpose of that huge image above was to make people understand that you can pass multiple objects to the assigned function. The assign function simply gets all the property from the target object and sets them to the target source any matching property value will be overwritten with the value of the last specified target source.

The Object.assign method is particularly useful if you want to create a shallow copy of your objects. The reason being if there is a value that references an object, In this case only the reference is copied.

As you could clearly see the property z of the object was referencing an object. When we changed its value. The value changed inside object b as well. The reason being it was just a reference. Our object.assign method here copied the reference to that object. If you want to create deep clone thought you can use alternatives like lodash.clone.

Hence, We see that While Object.create defines properties on our newly created Object. object.assign simply assigns the value of the targeted source objects to our target Object.

Leave a Reply