javascriptfunction

When I modify a parameter inside a function, why does the variable passed as the argument not change?


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?


Solution

  • 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"