0

I want to know if it is possible to pass a global variable in JavaScript by name to a function?

In my use case, I have two global variables abc and xyz. When function1() is called, I make an AJAX call and want to use the response to some work and assign value to variable abc. This same functionality exists for function2() and variable xyz. So I want to extract this assignValueToVariable() function and make it a util method.

But the problem is, if I pass the global variable name like I am doing in function2(), then xyz in global scope is always undefined. How can I make this work so that I can use the same assignValueToVariable() method in function1() and function2()?

HTML

<button type="button" onclick="otherfunction();">Click Me</button>

JavaScript

var abc,
    xyz;

function1();
function2();

function function1() {
  //ajax call - get data and pass it to function
  data = "123";
  // this works. Since I'm directly refering global variable in the function
  assignValueToVariableABC(data);
}

function function2() {
  //ajax call - get data;
  data = "456";
  // this doesn't set the value to global variable
  assignValueToVariable(xyz, data);
}

function otherfunction() {
  //xyz is undefined here
  console.log(abc + "--" + xyz);
}

function assignValueToVariable(varName, data) {
  //assign value from data to variable
  varName = data;
}

function assignValueToVariableABC() {
  //assign value from data to variable
  abc = data;
}
AGE
  • 3,752
  • 3
  • 38
  • 60
RKodakandla
  • 3,318
  • 13
  • 59
  • 79
  • That is not possible. It's because the javascript always pass by value, never pass by reference. So the value of the global variable would not change outside the scope. – DinoMyte Mar 15 '16 at 19:58
  • You can checkout [my answer to this question](http://stackoverflow.com/a/26020014/2324107). In your case, you need to pass a string `assignValueToVariable('xyz', data);` and then do `window[varName] = data`. But as stated in my answer, it is not recommanded... Why not simply `xyz = data`? – Karl-André Gagnon Mar 15 '16 at 20:02
  • 2
    If you really want global variables, why don't you just do `abc = data;` and `xyz = data;` ? There is not a lot you can abstract here. – Felix Kling Mar 15 '16 at 20:03
  • @FelixKling assigning values is not a single line of code in my actual use case. Those global variables contain objects like charts and data tables. I don't want to have 10-15 lines of code for the object initialization duplicated everywhere – RKodakandla Mar 15 '16 at 20:08
  • @RKodakandla: Then have a function that creates the object: `abc = createObjectFromData(data)`, `xyz = createObjectFromData(data)`. – Felix Kling Mar 15 '16 at 20:09
  • Why do you want to use global variables? – jbmartinez Mar 15 '16 at 20:18
  • Exactly, global variables are a bad idea, you pollute your global namespace – Jeanluca Scaljeri Mar 16 '16 at 08:04

2 Answers2

2

When you call assignValueToVariable(xyz, data); you are not passing in the variable name "xyz", you are passing the value that is stored in xyz, when you have simple types like strings and numbers. That's why assigning a value to varName doesn't change it outside that function, it's essentially a copy.

You could store the global data in an object, because then you can pass in a string to be used as a key:

var globalobject = {
    "xyz": "foo",
    "abc": "bar"
};

function function2() {
    assignValueToGlobal("xyz", 123);
}

function assignValueToGlobal(varName, data)
{
  globalobject[varName] = data;
}

function2();
console.log(globalobject);

To clarify further, in JavaScript primitive types (strings, numbers) are passed by value (essentially the value is copied and then passed). Objects are passed by copy of the reference pointing to the original, which is a bit quirky and different from many languages.

Sentri
  • 129
  • 4
  • *"because objects are passed by reference"* No they are not. Objects are represented **as** references. That has nothing to do with pass **by** reference. It's a common misconception. Pass by value and pass by reference refers to how bindings are evaluated. That's completely independent of the *value* those bindings hold. – Felix Kling Mar 15 '16 at 20:12
  • Thanks, I already fixed that sentence since it didn't relate much to my code sample. I think the most common way I've seen people explain it is "objects are passed by copies of references", which to me seems to be a good way to convey how they work. – Sentri Mar 15 '16 at 20:19
  • Yes. References, like any other values, are copied. – Felix Kling Mar 15 '16 at 20:21
0

Maybe you can use something like this:

function assignValueToVariable(globalObj, someKey) {
    return function (retVal) {
        globalObj[someKey] = retVal;
    };
}

var setAbc = assignValueToVariable(window, 'abc'),
    setXyz = assignValueToVariable(window, 'xyz');

makeAjaxCall(setAbc);
// etc
Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333