JavaScript — Data Mutation Explained
Data mutation in JavaScript can sometimes introduce hard to find bugs that’s why we need to know how the data is managed in JavaScript.
Like other languages, JavaScript has data type such as Number, String, Float, etc. which behaves as expected but one:- Object
Objects are key-value pairs in JavaScript and it can have nested objects of n-depth. A simple example is :
const obj = {name:’Ravi’,gender:’male’}
So what is the problem? The problem is when we copy such objects
So what happens when we copy the obj to a new variable obj2 and change value of name to “Bob”
const obj = {name:’Ravi’,gender:’male’}
const obj2 = obj;
obj2.name = ‘Bob’;
console.log(obj);
obj is changed!! interesting. But we didn’t make any change to obj but we made changes to obj2 so why this change affected obj?
Because when we assign an object to a variable in JavaScript it doesn’t copy the value of source object to destination variable but instead it assigns a reference of the source object to a variable, so we are just naming the same object twice. and that’s the confusion. So changing obj2 value will actually change the value of obj or even worse all the references of obj (if we have assigned it to some other variables as well ie. obj3, obj4 etc.) and this is actually mutating the original variable and if not aware this creates hard to find bug.