4

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"
}
Rajagopal 웃
  • 8,061
  • 7
  • 31
  • 43
  • Possible duplicate of http://stackoverflow.com/questions/373157/how-can-i-pass-a-reference-to-a-function-with-parameters – Dan Lister Jun 14 '12 at 15:15
  • check this out: http://snook.ca/archives/javascript/javascript_pass/ – kol Jun 14 '12 at 15:16
  • 1
    possible duplicate of [Pass a string by reference in Javascript](http://stackoverflow.com/questions/1308624/pass-a-string-by-reference-in-javascript) – Felix Kling Jun 14 '12 at 15:17
  • 1
    Possible duplicate of http://stackoverflow.com/questions/2423868/pass-variables-by-reference-in-javascript alemjerus's answer to that is probably what you want. Convert it to an object. – sachleen Jun 14 '12 at 15:17
  • 1
    @Dan, this doesn't seem to be a duplicate of that function. Here, the OP simply wants to know the best way to pass a function argument by reference in JS; the referenced question deals with references *to* a function object itself. – apsillers Jun 14 '12 at 15:20
  • I have referred all of the above links before posting it. It seems the answers are satisfied the persons who asked. But, not it was a better answer right! – Rajagopal 웃 Jun 14 '12 at 15:25

1 Answers1

3

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);
Angel
  • 1,180
  • 9
  • 13
  • 1
    This is mostly true, but [pedants will tell you that JavaScript is pure pass-by-value](http://stackoverflow.com/a/9070366/201952), and the *value* passed for objects is itself a reference. However, this is confusing, and from a practical standpoint, it basically looks like objects are passed by reference. – josh3736 Jun 14 '12 at 15:38
  • Well, yes, that is what I actually wanted to say. – Angel Jun 14 '12 at 15:41