I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
Related
I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval!
There is no single solution for this. It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
store those names/values as properties of an object and use bracket notation to look them up dynamically:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+ it's even easier to do this for existing variables using concise property notation:
// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};
var key = 'foo';
console.log(obj[key]);
If you have "consecutively" numbered variables, such as
// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));
then you should be using an array instead and simply use the index to access the corresponding value:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
If you are desperate to do this you can either try using eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
To reference a variable in JavaScript with only a string, you can use
window['your_variable_name']
You can set and reference variables, and objects in variables too.
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable hello in the global scope like this:
var hello = 'Hello, World!';
Let's encapsulate it inside an object. We'll call that object vv (variable variables):
var vv = {
'hello': 'Hello, World! ',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
console.log(vv[referToHello]); //Output: Hello, World!
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
var vv = {
'x': 'variable',
'variable': 'Hello, World!'
};
console.log(vv[vv['x']]); // Displays "Hello, World!"
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
Of course you can, but don't. The variables have to be global.
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
You can use the global window object, or this:
window:
var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123
Or using dot:
var data = "anyVariableName";
window.data = 123;
alert(window.data); //123
This:
ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123
or using dot
var data = "anyVariableName";
this.data = 123;
alert(this.data); //123
A real-life example:
var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
...
});
I do this with an object. No need to use window:
var myVars = {};
let foo = "hello";
myVars[foo] = 100;
let bar = myVars[foo];
just make sure myVars is global.
You can use the JavaScript eval(str) function.
This function converts the string provided into JavaScript code, and then executes it.
For example:
eval("console.log('Hello, World!')"); // Logs hello world
So to use it as a variable variable, you can do the following:
var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)