Search code examples
javascriptobject

Mutating Object property giving the preserved value not the modified one


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

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

Why is this behaving differently while passing a whole object or a object property in a temp variable ?


Solution

  • 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