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?
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.