Creating Immutable Objects

There are two main ways to create immutable objects:

  • Using Object.assign method

  • Using spread operator


Using Object.assign method:

The Object.assign method has the following syntax:

Object.assign(target, ...sources);


The target will contain all the merged sources.

Take a look at the below code:

const obj1 = { name: "David", age: 20 };
const obj2 = Object.assign({}, obj1, {name: "Mike"});

console.log(obj1); // { name: "David", age: 20 };
console.log(obj2); // { name: "Mike", age: 20 };
console.log(obj1 === obj2); // false

Always remember that the first argument passed to the Object.assign method will contain the results of the merging operation.

So in the above case, the empty object {} will be the target that will contain the result of the merge operation and that object will be returned by the Object.assign method which we're storing in obj2.

As the name property already exists in obj1, it will be overridden with the new provided value.

If there is no already existing name property then it will be added as a new property.

Also, as we've created a new empty object {} and merged all other objects into it, comparing obj1 with obj2 returns false as they're separate objects.

Using spread operator: 

Take a look at the below code:

const obj1 = { name: "David", age: 20 };
const obj2 = { ...obj1, name: "Mike" };

console.log(obj1); // { name: "David", age: 20 };
console.log(obj2); // { name: "Mike", age: 20 };
console.log(obj1 === obj2); // false

As you can see, we've used a spread operator to spread all the properties of the obj1 and then added a name property with the value of Mike.

So when comparing obj1 with obj2 returns false because they are separate objects.

Now take a look at the below code:
 

const obj1 = { name: "David", age: 20 };
const obj2 = { name: "Mike" };
const obj3 = { ...obj2, ...obj1, name: "John"};

console.log(obj1); // { name: "David", age: 20 };
console.log(obj2); // { name: "Mike" };
console.log(obj3); // { name: "John", age: 20 };
console.log(obj1 === obj2); // false
console.log(obj2 === obj3); // false

As you can see, while assigning a new object to obj3 we're spreading out all the properties of obj2 first then obj1 and then adding a name property.

So here, we're not changing any object but creating a new obj3 object by merging the properties of obj1 and obj2.

You can use either Object.assign method or the spread operator to create an immutable object. 

We will be using the spread operator for creating a new array as it's easy to understand and is a preferred way of creating new objects when working in React.