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.