Object.assign

What is it?

According to the MDN page:

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Why is it important?

This is a good way to deal with the concept of immutable objects. Immutability is an important concept throughout React and Redux design methodology. By definition, immutable means “unchanging over time or unable to be changed.” In the context of React / Redux applications, we are normally referring to an object that represents the current state of your application.

Example

var obj1 = {
property1 : "some value",
property2 : "another value"
};

var newObject = Object.assign({}, obj1, {property3 : "yet another value"});

console.log(newObject);

The console output here will show:

Object {
property1: "some value",
property2: "another value",
property3: "yet another value"
}

The important point here is that we have not altered obj1 directly by doing obj1.property3 = “yet another value” – we have created a new object that looks exactly the same as if we had done that. But the prior state is preserved in obj1.

One noteable feature of Object.assign: properties are overwritten by other objects that have the same properties later in the parameters order – which makes this method a useful way to add properties OR update existing properties for your target object.

Object.assign was introduced as part of ES6 and is now available in Firefox (34+) and Chrome (45+).