/

The Object assign() Method: A Closer Look

The Object assign() Method: A Closer Look

The assign() method is a useful feature introduced in ES2015 for the Object object in JavaScript. It allows you to copy all the enumerable own properties from one or more objects into another object.

The primary purpose of assign() is to create a shallow copy of an object. It means that the values of the properties are cloned, but the object references are copied instead of creating new objects. This implies that if you modify a property in the original object, the corresponding property in the copied object will also be modified.

Let’s consider an example to better understand this behavior:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const original = {
name: 'Fiesta',
car: {
color: 'blue'
}
};

const copied = Object.assign({}, original);

original.name = 'Focus';
original.car.color = 'yellow';

console.log(copied.name); // Output: Fiesta
console.log(copied.car.color); // Output: yellow

In the above example, we have an original object with a property called name and an inner object called car. We create a shallow copy of the original object using assign(), and assign it to the copied object. When we modify the name property in the original object, the change is not reflected in the copied object. However, when we modify the car.color property, as it is referring to the same inner object, the change is reflected in both objects.

Furthermore, the assign() method can also copy properties from multiple source objects into a single target object. Consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
const wisePerson = {
isWise: true
};

const foolishPerson = {
isFoolish: true
};

const wiseAndFoolishPerson = Object.assign({}, wisePerson, foolishPerson);

console.log(wiseAndFoolishPerson);
// Output: { isWise: true, isFoolish: true }

In this example, we have two source objects, wisePerson and foolishPerson, and we use assign() to combine their properties into a new object called wiseAndFoolishPerson. The resulting object contains all the properties from both source objects.

In summary, the assign() method in JavaScript provides a convenient way to create a shallow copy of an object and merge properties from multiple objects into a single object. Keep in mind the behavior of object references when using this method.

tags: [“JavaScript”, “Object.assign”, “ES2015”, “shallow copy”]