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;
}