Flanagan's "JavaScript - The Definitive Guide" gives the following on page 653:
var variables = ""
for (var name in this)
variables += name + "\n";
Answer from user181548 on Stack OverflowGet all Javascript Variables? - Stack Overflow
Is there a JavaScript equivalent of PHP’s “variable variables”? - Stack Overflow
How do JavaScript’s global variables really work?
Question: Most efficient way to use variables to avoid GC?
Videos
Flanagan's "JavaScript - The Definitive Guide" gives the following on page 653:
var variables = ""
for (var name in this)
variables += name + "\n";
For Firefox, you can see the DOM tab -- easy, though not an answer to your question.
The for in loop provided in Kinopiko's answer will work, but not in IE. More is explained in the article linked below.
For IE, use the RuntimeObject.
if(this.RuntimeObject){
void function() {
var ro = RuntimeObject(),
results = [],
prop;
for(prop in ro) {
results.push(prop);
}
alert("leaked:\n" + results.join("\n"));
}();
}
See also:
- Detecting Global Pollution with the JScript RuntimeObject (DHTML Kitchen article)
- RuntimeObject (MSDN docs)
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]);