Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

The Object.assign() Method In JavaScript

4.43/5 (3 votes)
27 Jan 2021CPOL3 min read 3.7K  
Object.assign() and some things to be remembered when dealing with this method
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.

JavaScript
/*
 * Let's define an object with two properties
 */
const desktop = {
  CPU: "Intel",
  Memory: "16GB"
};

/*
 * Let's define a property at runtime. 
 * This property we'll set as non-enumerable.
 */
Object.defineProperty(desktop, 'Operating_System', {
  value: "Windows 10",
  enumerable: false
});

/* Let's try to iterate through the properties of the desktop object.
 * Expected: 
   "CPU" 
   "Memory"
   The property desktop won't appear as we iterate 
   because the enumerable property is set to false.
 */ 

for( let keys in desktop){
  console.log(keys);
}

//Same as using Object.keys() methods
console.log(Object.keys(desktop));

Here are the steps of the sample code above.

  1. 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.
  2. 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.
  3. 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.

JavaScript
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:

JavaScript
/*
* In this example, let's declare two objects, in our example, food and clothes. 
* After that, let's try to merge the two objects into one.
 */

//declare two objects
const food = { color: 'blue'};
const clothes = { brand: 'Guess'};
//merge two objects
const result = Object.assign({ companyName: "XYZ" }, food, clothes);

//The output would be:{companyName: "XYZ", color: "blue", brand: "Guess"}
console.log(result); 

Clone an Object

With the use of Object.assign(), we can clone objects.

See the example below:

JavaScript
/*
 * In this example, let's declare one object and clone it into an empty object. 
 */

//declare an object
const customer = { fName: 'Jin', lName: 'Necesario', handsome: true };
//clone the customer object
const clonedCustomer = Object.assign({}, customer);

//The output would be: {fName: "Jin", lName: "Necesario", handsome: true}
console.log(clonedCustomer);

Things to Remember about Object.assign() Method

The [[prototype]] property of sources isn't copied.

Let's see an example below:

JavaScript
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";

/*
* Person {firstName: "jin", lastName: "necesario", age: 100, eyeColor: "brown"}
* age: 100
* eyeColor: "brown"
* firstName: "jin"
* lastName: "necesario"
* __proto__:
* nationality: "English"
* constructor: ƒ Person(first, last, age, eyecolor)
* __proto__: Object
*/
console.log(newPerson);

/*output english*/
console.log(newPerson.nationality);
console.log(newPerson.__proto__.nationality);

let result = Object.assign({}, newPerson);

console.log(result);

/*undefined because no access to [[proto]]*/
console.log(result.nationality);
console.log(result.__proto__.nationality);

It doesn't copy getters and setters.

Let's see an example below:

JavaScript
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);

/*
* We are showing that this object has a getter and setter that will be 
* available in the target object
* {enumerable: true, configurable: true, get: ƒ, set: ƒ}
*   configurable: true
*   enumerable: true
*   get: ƒ fullName()
*   set: ƒ fullName(value)
*   __proto__: Object
*/

console.log(Object.getOwnPropertyDescriptor(customer,'fullName'));

/*
 * Output: 
 * { fName: "Jin", lName: "Necesario", fullName: "Necesario, Jin"}
 */
console.log(result);

/*
* Output: 
* {value: "Necesario, Jin", writable: true, enumerable: true, configurable: true}
*  configurable: true
*  enumerable: true
*  value: "Necesario, Jin"
*  writable: true
*  __proto__: Object
*/
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.

JavaScript
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);

/**
 * output:
 * {
     details: {firstName: "Vincent"}
     id: 2
    }
 */
console.log(newCustomer);

/**
 *  output:
 *  {
 *    details: {firstName: "Vincent", lastName: "Necesario", tall: true}
 *    id: 2
 *   }
 */
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()

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)