Unlike PHP, JavaScript does not offer access to the globals array (which contains references to all declared variable names). Therefore, JavaScript does not offer native support for variable variables. You can, however, emulate this function as long as you define all of your variables as part of an array or object. This, in turn, will create an array of villains for you. For example, instead of declaring a hello variable in the global scope:
var hello = 'hello world';
let it encapsulate it inside the object. We will call this object vv (variable variables):
var vv = { 'hello': 'hello world',
Now we can refer to the variable at this index, and since array indices can be provided using the variable, we actually use the variable variable:
console.log(vv[referToHello]);
The answer to your question
Apply this to the code provided in the original question:
var vv = { 'x': 'variable', 'variable': 'hello world!' }; console.log(vv[vv['x']]);
Practical use
While the previous code may seem ridiculously cumbersome and impractical, there are practical uses of variable variables in JavaScript using this type of encapsulation. In the example below, we use the same concept to get the undefined identifier of the 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 identifier of each element and assigns the node of the specified element as the value of each variable. And since the use of global variables in JavaScript is usually not recommended, variable variables are a unique area (in this case, declaring them inside an elementIds array), not only neat, but also more responsible.