“Variable” variables in Javascript?How to convert array values to variablesdynamic (variable) variables (as in php?)Dynamic javascript variable name using for loopset jquery variable name as DIV id name'Dynamic' Javascript Array Name?How can I use a key value as a variable name in JavaScript?Array push data from a parameter valueWant to create a dynamic array from javascript promptHow to dynamically define arrays in javascript?Attribute value as variable nameHow do JavaScript closures work?Convert JavaScript String to be all lower case?What's the difference between using “let” and “var”?How do you check if a variable is an array in JavaScript?How do I include a JavaScript file in another JavaScript file?How can I display a JavaScript object?Sort array of objects by string property valueWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?
Is there a way to convert blue ice back into packed ice?
How did Lefschetz do mathematics without hands?
How did they film the Invisible Man being invisible, in 1933?
My colleague is constantly blaming me for his errors
13th chords on guitar
What is quadratization?
Why can't you move another user's directory when you can move their file?
Ways to get SMD resistors from a strip
What verb for taking advantage fits in "I don't want to ________ on the friendship"?
Making a wall made from glass bricks
Closest Proximity of Oceans to Freshwater Springs
Adjective for 'made of pus' or 'corrupted by pus' or something of something of pus
On what to compliment someone with anorexia in order to improve their body image?
Can European countries bypass the EU and make their own individual trade deal with the U.S.?
How can I deal with extreme temperatures in a hotel room?
Reusable spacecraft: why still have fairings detach, instead of open/close?
Is it possible to have a character with proficiency in all martial weapons without proficiency in Medium armor?
Why did the Apple //e make a hideous noise if you inserted the disk upside down?
Story where diplomats use codes for emotions
Traversing Eurasia: A Cryptic Journey
Can a successful book series let the bad guy win?
Why wasn't EBCDIC designed with contiguous alphanumeric characters?
What European countries have secret voting within the Legislature?
I just started should I accept a farewell lunch for a coworker I don't know?
“Variable” variables in Javascript?
How to convert array values to variablesdynamic (variable) variables (as in php?)Dynamic javascript variable name using for loopset jquery variable name as DIV id name'Dynamic' Javascript Array Name?How can I use a key value as a variable name in JavaScript?Array push data from a parameter valueWant to create a dynamic array from javascript promptHow to dynamically define arrays in javascript?Attribute value as variable nameHow do JavaScript closures work?Convert JavaScript String to be all lower case?What's the difference between using “let” and “var”?How do you check if a variable is an array in JavaScript?How do I include a JavaScript file in another JavaScript file?How can I display a JavaScript object?Sort array of objects by string property valueWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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?
javascript variables variable-variables
add a comment |
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?
javascript variables variable-variables
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32
add a comment |
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?
javascript variables 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?
javascript variables variable-variables
javascript variables variable-variables
edited Jan 28 at 20:48
Bergi
393k65 gold badges613 silver badges938 bronze badges
393k65 gold badges613 silver badges938 bronze badges
asked Mar 3 '11 at 22:40
ShoeLace1291ShoeLace1291
1,6849 gold badges31 silver badges57 bronze badges
1,6849 gold badges31 silver badges57 bronze badges
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32
add a comment |
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32
add a comment |
7 Answers
7
active
oldest
votes
There is no single solution for this (well, there is eval, but lets not seriously consider that). 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
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));store the those name/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
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]);
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
add a comment |
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]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
evalcan't create local variables in strict mode. An indirect call can create global variables, though.
– Oriol
Nov 27 '16 at 22:41
add a comment |
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.
add a comment |
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 gloabls 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 it's 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.
add a comment |
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])
add a comment |
var vars = ;
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
add a comment |
You can use the JavaScript eval(str) function.
What this function does is convert the string provided into JS code, 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.)
add a comment |
protected by Samuel Liew♦ Nov 29 '16 at 3:26
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
There is no single solution for this (well, there is eval, but lets not seriously consider that). 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
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));store the those name/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
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]);
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
add a comment |
There is no single solution for this (well, there is eval, but lets not seriously consider that). 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
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));store the those name/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
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]);
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
add a comment |
There is no single solution for this (well, there is eval, but lets not seriously consider that). 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
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));store the those name/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
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]);There is no single solution for this (well, there is eval, but lets not seriously consider that). 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
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));store the those name/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
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]);// BAD
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));// BAD
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));// GOOD
var obj =
foo: 42,
bar: 21,
;
var key = 'foo';
console.log(obj[key]);// GOOD
var obj =
foo: 42,
bar: 21,
;
var key = 'foo';
console.log(obj[key]);// GOOD
var foo = 42;
var bar = 21;
var obj = foo, bar;
var key = 'foo';
console.log(obj[key]);// GOOD
var foo = 42;
var bar = 21;
var obj = foo, bar;
var key = 'foo';
console.log(obj[key]);// BAD
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));// BAD
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';
var index = 1;
console.log(eval('foo' + index));// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);edited Nov 8 '18 at 23:47
answered Mar 3 '11 at 22:56
Felix KlingFelix Kling
577k134 gold badges889 silver badges954 bronze badges
577k134 gold badges889 silver badges954 bronze badges
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
add a comment |
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
Examples for defining multiple values: var x=1; var x,y=2; x=1; var x=1,y=2; var x=xx=1; var y=x+x;
– Amin Maleki
Apr 30 at 15:40
add a comment |
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]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
evalcan't create local variables in strict mode. An indirect call can create global variables, though.
– Oriol
Nov 27 '16 at 22:41
add a comment |
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]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
evalcan't create local variables in strict mode. An indirect call can create global variables, though.
– Oriol
Nov 27 '16 at 22:41
add a comment |
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]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
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]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
answered Mar 3 '11 at 22:51
MasterbuddhaMasterbuddha
5943 silver badges9 bronze badges
5943 silver badges9 bronze badges
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
evalcan't create local variables in strict mode. An indirect call can create global variables, though.
– Oriol
Nov 27 '16 at 22:41
add a comment |
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
evalcan't create local variables in strict mode. An indirect call can create global variables, though.
– Oriol
Nov 27 '16 at 22:41
15
15
+1 for the window solution
– DanMan
May 14 '13 at 13:53
+1 for the window solution
– DanMan
May 14 '13 at 13:53
eval can't create local variables in strict mode. An indirect call can create global variables, though.– Oriol
Nov 27 '16 at 22:41
eval can't create local variables in strict mode. An indirect call can create global variables, though.– Oriol
Nov 27 '16 at 22:41
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 9 '14 at 0:50
Awesomeness01Awesomeness01
1,5201 gold badge8 silver badges13 bronze badges
1,5201 gold badge8 silver badges13 bronze badges
add a comment |
add a comment |
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 gloabls 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 it's 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.
add a comment |
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 gloabls 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 it's 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.
add a comment |
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 gloabls 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 it's 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.
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 gloabls 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 it's 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.
answered Nov 20 '17 at 11:22
NadavNadav
4933 silver badges14 bronze badges
4933 silver badges14 bronze badges
add a comment |
add a comment |
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])
add a comment |
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])
add a comment |
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])
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])
answered Oct 13 '12 at 18:07
Konrad BorowskiKonrad Borowski
7,6142 gold badges42 silver badges62 bronze badges
7,6142 gold badges42 silver badges62 bronze badges
add a comment |
add a comment |
var vars = ;
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
add a comment |
var vars = ;
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
add a comment |
var vars = ;
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
var vars = ;
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
answered Mar 10 '14 at 13:05
lkdhruwlkdhruw
3531 gold badge3 silver badges16 bronze badges
3531 gold badge3 silver badges16 bronze badges
add a comment |
add a comment |
You can use the JavaScript eval(str) function.
What this function does is convert the string provided into JS code, 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.)
add a comment |
You can use the JavaScript eval(str) function.
What this function does is convert the string provided into JS code, 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.)
add a comment |
You can use the JavaScript eval(str) function.
What this function does is convert the string provided into JS code, 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.)
You can use the JavaScript eval(str) function.
What this function does is convert the string provided into JS code, 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.)
answered Jul 12 '17 at 21:55
Abraham Murciano BenzadonAbraham Murciano Benzadon
5553 silver badges13 bronze badges
5553 silver badges13 bronze badges
add a comment |
add a comment |
protected by Samuel Liew♦ Nov 29 '16 at 3:26
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
arrays are not variables, if you use an array as a function argument , the JS interpreter will use a pointer to your array. In programming the use of certain terms is precise, and what you ask for has only very little meaning
– Mister Jojo
Dec 6 '18 at 0:32