In this blog we will learn about object mutation in JavaScript We will learn why it is so important to learn about mutation in Javascript We will also discuss why mutation is bad and how to solve data mutation problem
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 nonprimitive 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 nonpredictable side effects They also reduce code performance with increased memory usage
Lets 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 objects memory location The variables dont actually contain the value Keeping this in mind lets see what happens when we change the object value
For example lets create a car object
const car { name BMW }We know that we can easily add new properties to an object by setting them directly So lets add a new property color to the car object
carcolor black consolelogcarAdding a new property to a car object is object mutation Lets add one more scenario and see the objects mutation side effect
Create a new variable newCar and assign car object to it
const car { name BMW } const newCar carLets change its color property and see what happens
newCarcolor blue consolelogcar object consolelogcar consolelognewCar object consolelognewCarIf 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 objects 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 inmemory value The change in the newCar object would affect car object automatically as well
How to prevent objects from mutating
Using thirdparty libraries
You can use small Immutablejs 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 inplace but instead always yields new updated data
Using Objectassign
You can use Objectassign method to prevent objects from mutating Using Objectassign you can combine two or more objects together into a single target object It will return the target object Here is the syntax
const newObject ObjectassigntargetObject SourceObject const manager { role manager } const salary { salary 50000 } const staff Objectassignsalary manager consolelogstaffIn the above example both objects are merged into a new object Lets check both manager and salary objects and see any side effects on them
consolelogmanagerOur manager object is safe and we are able to prevent it from mutating Thats great Lets check another objects salary as well
consolelogsalaryHave 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 Objectassign Objectassign mutate the first object and other objects never get mutated Lets see how to solve this problem
How to solve Objectassign 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 Lets see how to solve this
const staff Objectassign{} salary managerConclusion
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