This page looks best with JavaScript enabled

Object Mutation In JavaScript

 ·  ☕ 5 min read  ·  ✍️ Adesh

What is data mutation in JavaScript?

Mutation means a change in the form or nature of the original data. In JavaScript, there are two data types: 1) primitive and 2) non-primitive/reference data types.

Primitive data types are Boolean, Number, String, Null and Undefined. Primitive data types are referenced by value. Primitive types in JavaScripts are immutable, meaning that if we change one then a new instance is created as a result.

Reference data types are Objects and Arrays. Reference types in JavaScript are  mutable, meaning that the state and fields of mutable types can be changed. No new instance is created as a result.

Why mutation is bad programming?

The mutation is a bad programming practice. If your code is mutable, you might change or break something without knowing. The code becomes harder to read and test, produces non-predictable side effects. They also reduce code performance with increased memory usage.

Let’s understand above statement by object mutation in JavaScript.

Object mutation in JavaScript

Objects are mutable in JavaScript. As I told above, objects are reference typed data. Therefore, they contains the reference to the value. This reference points to the object’s memory location. The variables don’t actually contain the value. Keeping this in mind, let’s see what happens when we change the object value.

For example, let’s create a car object.

1
const car = { name: BMW };

We know that we can easily add new properties to an object by setting them directly. So, let’s add a new property color to the car object.

1
2
car.color = black;
console.log(car);

Adding a new property to a car object is object mutation. Let’s add one more scenario and see the object’s mutation side effect.

Create a new variable newCar and assign car object to it.

1
2
const car = { name:  BMW };
const newCar = car;

Let’s change its color property and see what happens.

1
2
3
4
5
newCar.color = blue;
console.log(car object);
console.log(car);
console.log(newCar object);
console.log(newCar);

If you noticed in the console log, the BMW car object color also changed to blue, whereas I just changed the color of the newCar object.

By mutating the newCar object, car object get mutated automatically without your knowledge. These kinds of unpredictable changes in your code can break your application unexpectedly. These kinds of bugs are hard to debug and fix.

Why original object mutated?

The reason behind this is — objects are reference type data. Whenever you create an object, it gets a new memory location. This memory location holds the object’s value. Then this memory location links to the variable name.

So, when I created the newCar object using const newCar = car, the car memory is shared by this newCar object. Both have now the same in-memory value. The change in the newCar object would affect car object automatically as well.

How to prevent objects from mutating?

Using third-party libraries

You can use small Immutable.js library to prevent objects from mutating. As per this library —

Immutable data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic. Persistent data presents a mutative API which does not update the data in-place, but instead always yields new updated data.

Using Object.assign()

You can use Object.assign() method to prevent objects from mutating. Using Object.assign(), you can combine two or more objects together into a single target object. It will return the target object. Here is the syntax:

1
2
3
4
5
const newObject = Object.assign(targetObject, SourceObject);
const manager = { role: "manager" };
const salary = { salary: "$50,000" };
const staff = Object.assign(salary, manager);
console.log(staff);

In the above example, both objects are merged into a new object. Let’s check both manager and salary objects and see any side effects on them.

1
console.log(manager);

Our manager object is safe and we are able to prevent it from mutating. That’s great. Let’s check another object’s salary as well.

1
console.log(salary);

Have you noticed any change in salary object? We got the role property from the manager object, which was not expected.

Note: Always remember this point while using Object.assign(). Object.assign() mutate the first object, and other objects never get mutated. Let’s see how to solve this problem.

How to solve Object.assign() mutation problem

In order to solve the above problem, you should pass a new empty object( {} ) at first place. This empty object prevents other objects from mutating. Let’s see how to solve this.

1
const staff = Object.assign({}, salary, manager);

Conclusion

In this blog, we learned about data mutation in JavaScript. Why it is important to understand the object mutation and how to solve it in your day to day JavaScript programming.

Further Reading

Create A React App With Webpack And Babel

What Is JavaScript Callback And How Does It Work?

Add An Item To An Array Using JavaScript Splice()

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect