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"
}
6

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This is mostly true, but pedants will tell you that JavaScript is pure pass-by-value, 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.
Well, yes, that is what I actually wanted to say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.