Skip to content Skip to sidebar Skip to footer

Automatically Updating The Actual Parameters In Javascript

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 = '

Solution 1:

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";
        functionmyFunction(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);

Post a Comment for "Automatically Updating The Actual Parameters In Javascript"