Search code examples
typescriptpass-by-reference

Object variable isn't updated inside a method


I am trying to update an object passed as a parameter to a method in my typescript code, but it never changes:

export class MyClass {

  //...
  myMethod(array) {
    //...
    let myVariable: MyObject;
    array.forEach(currentElement => {
      if (someCondition) {
        this.replaceVariable(myVariable, currentElement);
      }
    });

    console.log(myVariable); // myVariable here is Undefined

    return myVariable;
  }

  private replaceVariable(variableToReplace: MyObject, newValue: MyObject) {
    if (variableToReplace == null) {
      variableToReplace = newValue;
    } else {
      if (someCondition) {
        variableToReplace = newValue;
      }
    }

    console.log(variableToReplace); // variableToReplace here is replaced by newValue
  }
}

As objects are always passed by reference, I was expecting that myVariable gets the new value after calling the method replaceVariable. But as you can see in the code comments, the variable is replaced inside the replaceVariable method, and keeps an undefined value in myMethod


Solution

  • As objects are always passed by reference, I was expecting that myVariable gets the new value after calling the method replaceVariable

    Yes they are passed by reference. However they are not passed as out varaibles. You can mutate, but you cannot reassign.

    Difference

    Since JavaScript doesn't have support for out variables, here is a C# reference for the two so you can understand the difference: