I'm doing the following sort of code in a project of mine, and the result of it is confusing me.
function changeSomethingsValue (thingToChange) {
thingToChange = "something else";
}
var something = "something";
changeSomethingsValue(something);
console.log(something); // prints out "something"
I'm confused as to why the value of the something variable is still the string "something" after it had been passed through the changeSomethingsValue function. Why is this happening and how do I get the function to assign the new value to whatever variable gets passed in?
2 Answers 2
Parameters are passed by value, not by reference. In the case of a string, the parameter is a copy of the reference to the string. Changing the copy inside the function by assigning a new reference to it won't change the original.
If you pass in an object or array, you can change the items in them without the need to change the reference to the object or array:
function changeSomethingsValue(thingToChange) {
thingToChange[0] = "something else";
}
var something = [ "something" ];
changeSomethingsValue(something);
console.log(something[0]); // prints out "something else"
A common pattern when a function should have one value as input and a changed value as output is to return the value:
function changeSomethingsValue(thingToChange) {
return thingToChange + " else";
}
var something = "something";
something = changeSomethingsValue(something);
console.log(something); // prints out "something else"
Comments
When passing primitives, like a string or a number, it's passed by value. What you're expecting is for it to be passed by reference.
The fix would be to set something to the return value of changeSomethingsValue
function changeSomethingsValue (thingToChange) {
thingToChange = "something else";
return thingToChange;
}
var something = "something";
something = changeSomethingsValue(something);
console.log(something); // prints out "something"
5 Comments
return keyword in the function.thingToChange parameter and pass something into the function.something which I do believe is what he was looking for -- not a deep understanding of passing references around in javascript.
with, fancy things like getters).