Automatically updating the actual parameters in javascript

javascript

Solution

Primitive types, that is strings/numbers/booleans are passed by value. Objects such as functions, objects, arrays are "passed" by reference.

So, what you want won't be possible, but the following will work:

        var myObj = {};
        myObj.str = "this is a string";
        function myFunction(obj){
            // automatically have to reflect the change in str when i change the arg value
            obj.str = "This is new string";
            // Expected value of str is "This is new string"
        }
        myFunction(myObj);
        console.log(myObj.str);

Problem

How to pass a primitive variable (like a string) by reference when calling a java script method? Which is equivalent of out or ref keyword in C#. I have a variable like `var str = "this is a string";` and passing the str into my function and automatically have to reflect the change in str when i change the argument value ``` function myFunction(arg){ // automatically have to reflect the change in str when i change the arg value arg = "This is new string"; // Expected value of str is "This is new string" } ```

Original source

Related problems