In this post, we'll see a quick illustration of the Object.assign() and some things that need to be remembered when using this method.
Introduction
The first time I saw this method, I assumed that this method could help me copy objects or merge objects into one. As I got comfortable using this method, I became more curious, and I wanted to know more about it and its different behaviors.
That's why this post will explore this method and the things that you need to remember when using this method.
OK, let's get started.
Table of Contents
What is Object.assign()?
Once invoked, this method copies the values from one or more different objects to a target object. Moreover, the values copied are all of the owned enumerable properties of an object. Those who don't understand enumerable properties, no worries, we'll learn it together and show a straightforward example.
JavaScript Enumerable Property
An enumerable property in JavaScript is a property that can be visited using the for-in loop
or similar iteration methods, like Object.keys()
.
Let's have a quick example of how to check if a property is enumerable.
const desktop = {
CPU: "Intel",
Memory: "16GB"
};
Object.defineProperty(desktop, 'Operating_System', {
value: "Windows 10",
enumerable: false
});
for( let keys in desktop){
console.log(keys);
}
console.log(Object.keys(desktop));
Here are the steps of the sample code above.
- We have declared one object that has two properties. And these properties are enumerable (set to
true
), which is the default behavior of JavaScript when creating an object. - In this second step, we have used the
static
method Object.defineProperty()
to add a property to the object and set its enumerable property to false
. - Then we have tried both the
for
-in
loop and Object.keys()
method. As expected, these two methods can get the CPU
and Memory
properties except for the property OperatingSystem
.
Syntax & Parameters
Going back to the Object.assign()
method, we'll try to explore its syntax and parameters.
For the syntax, it looks straightforward.
Object.assign(target, ...sources)
The first parameter is the target object. In simple terms, this target
object will be the result of the different sources combined.
The second parameter is the sources
, and they are the objects you want to apply.
Lastly, this method returns the target object.
What Can You Do With Object.assign() Method?
Merge an Object
With the use of Object.assign()
, we can merge objects.
See the example below:
const food = { color: 'blue'};
const clothes = { brand: 'Guess'};
const result = Object.assign({ companyName: "XYZ" }, food, clothes);
console.log(result);
Clone an Object
With the use of Object.assign()
, we can clone objects.
See the example below:
const customer = { fName: 'Jin', lName: 'Necesario', handsome: true };
const clonedCustomer = Object.assign({}, customer);
console.log(clonedCustomer);
Things to Remember about Object.assign() Method
The [[prototype]] property of sources isn't copied.
Let's see an example below:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const newPerson = new Person("jin", 'necesario', 100, 'brown');
Person.prototype.nationality = "English";
console.log(newPerson);
console.log(newPerson.nationality);
console.log(newPerson.__proto__.nationality);
let result = Object.assign({}, newPerson);
console.log(result);
console.log(result.nationality);
console.log(result.__proto__.nationality);
It doesn't copy getters and setters.
Let's see an example below:
const customer = {
fName: 'Jin',
lName: 'Necesario',
get fullName() {
return this.lName + " " + this.fName;
},
set fullName(value){
const parts = value.split(" ");
this.fName = parts[0];
this.lName = parts[1];
}
};
let result = Object.assign({}, customer);
console.log(Object.getOwnPropertyDescriptor(customer,'fullName'));
console.log(result);
console.log(Object.getOwnPropertyDescriptor(result,'fullName'));
Difference between $.extend and Object.assign()?
If you have been using the JQuery and Vanilla JS side by side, you might have come across with $.extend
in JQuery. You probably have thought or asked about the difference between the two.
Now, in my view, these methods have the same objective to clone or merge objects into one.
However, the main difference is that Object.assign()
only do a shallow copy while $.extend
uses deep copy.
Let us see an example below.
let customer = {
id: 1,
details: {
firstName: 'Jin',
lastName: 'Necesario',
tall: true
}
};
let customer2 = {
id: 2,
details: {
firstName: 'Vincent'
}
};
let newCustomer = Object.assign({}, customer, customer2);
let newCustomer2 = $.extend(true, {}, customer, customer2);
console.log(newCustomer);
console.log(newCustomer2);
Summary
This post has shown what the Object.assign()
method can actually do with code samples, and we have also shown some of the things that you need to be aware of when dealing with this method.
I hope you have enjoyed this article, as I have enjoyed writing it. Stay tuned for more. Until next time, happy programming!
History
- 28th January, 2021: Initial version.
- 13th February, 2021: Added the concept of the difference between
$.extend
and Object.assign()