Search code examples
javascriptobjectpass-by-reference

If JavaScript objects are passed by reference, why doesn't updating the property value update the local variable


Objects are passed around by reference. They are never copied.

I have a code segment as following:

var person = { firstname: 'John', lastname: 'Smith' }
var anotherPerson = person

anotherPerson.nickname = 'Curly'
console.log(person.nickname)
// "Curly"

var fname=person.firstname
console.log(fname)
// "John"

person.firstname = 'Tom'
console.log(anotherPerson)
// Object { firstname: "Tom", lastname: "Smith", nickname: "Curly" }

console.log(fname)
// "John" <-- fname is not updated

My question is after I updated the object person's firstname to Tom, why the local variable fname is not updated?


Solution

  • Values in Javascript are never passed by reference, always by value. Those values themselves are references in case of objects.

    The fact that even objects are passed by value should be clear if you consider that a function receiving person as an argument can only change its content, it can't replace the whole value of the person variable. That's the same for fname, with the additional limit that strings are immutable which means that a function receiving the value of the fname variable can't change this variable at all.