I was playing around with the JavaScript objects by mutating the property values and find this observation.
Problem statement : I am mutating an object property value inside a function and returning the object but somehow it preserved the previous value and not giving the updated one.
const obj = { prop: 5 }
const mutatingObjectFunction = () => {
let temp = obj.prop;
obj.prop = 10;
return temp;
}
console.log(mutatingObjectFunction()); // 5
Can someone help me in understanding, Why it is returning 5 and not 10 ?
If I will assign directly an object instead of its property to a temp variable, then it is giving me the updated value.
const obj = { prop: 5 }
const mutatingObjectFunction = () => {
let temp = obj;
obj.prop = 10;
return temp;
}
console.log(mutatingObjectFunction().prop); // 10
Can someone help me to understand why this is behaving differently while passing a whole object
or a object property
in a temp
variable ?
CodePudding user response:
You can't pass a primitive property by reference in JS. So what you're passing to temp
isn't obj.prop
, but just 5
.
But when you pass an object, you're passing a refernce to that same object instance so mutating that object can reflect in all references to it.
let testObj = [] // Arrays are objects too
let a = {obj : testObj}
let temp = a.obj // temp is now a reference to the same array
a.obj.push(1)
temp.push(2)
console.log(temp)
let a = {obj: {value: 5}} // We use an object, {value: 5}
let temp = a.obj // temp is now a reference to our object
a.obj.value
temp.value
console.log(temp.value) // 7
CodePudding user response:
As per JavaScript here
let temp = obj;
you or not cloning the object
you referencing a object
. If you want to clone the object
you should use Spread operator like this let temp = {...obj};
As per you second example you are referencing a object. so if you changed the actual object value it's also affect referenced temp
value
But in the first example you are not assigning complete object
instead you assigning a particular value of the object. so here you making a coping the value let temp = obj.prop;
. so it won't affected when the actual value is changed