Reputation: 7771
In this simple script, I try to change the value of the string contained in a.person
. Why does it not update the object.property
's value?
function searchObject(object, value) {
object = value;
}
var a = {
person: "Ian"
};
searchObject(a.person, "James");
document.write(a.person);
I thought that the output should be "James", not "Ian". Why does it not update my object?
Upvotes: 2
Views: 293
Reputation: 19112
What you are doing now is replacing the local variable object
with the value value
. What you could do instead to achieve this is:
function searchObject(object, property, value) {
object[property] = value;
}
var a = {
person: "Ian"
};
searchObject(a, 'person', "James");
document.write(a.person);
Then you wouldn't be replacing the local variable, but the property of the object. The object still refers to the same thing, and in this code, you're editing the object, instead of locally replacing it.
This is because in JavaScript, every function argument is passed by value, but since objects are stored as pointers, not as their value, that means that you're only given the memory address of the object if you put a
in your function parameter. If you then access that variable within the function again, it will be a pointer to the same thing. Changing properties in it then will change the properties in the actual object too.
Upvotes: 6
Reputation: 1680
You are passing in a.person
as the object, but a.person
is a string value. Strings are passed by value in JavaScript, not by reference. This means that the object
in your function is essentially a copy of the string "Ian"
and not the actual value of a.person
Upvotes: 2
Reputation: 227200
This is because only objects are passed by reference. Everything else is passed by value. If you wanted this to work, you could try this:
function searchObject(object, key, value) {
object[key] = value;
}
var a = {
person: "Ian"
};
searchObject(a, "person", "James");
document.write(a.person);
Upvotes: 4