4

How can I make the code that follows to work?

var x = 'name';

and then, to use the value inside x, as it was a variable, and set it, so that if i want it to be NAME, i'll have the result:

var name = 'NAME';

Is it possible ?

2

2 Answers 2

11

Not directly, no. But, you can assign to window, which assigns it as a globally accessible variable :

var name = 'abc';
window[name] = 'something';
alert(abc);

However, a much better solution is to use your own object to handle this:

var name = 'abc';
var my_object = {};
my_object[name] = 'something';
alert(my_object[name]);
Sign up to request clarification or add additional context in comments.

Comments

5

I haven't seen the rest of your code, but a better way might be to use an object.

var data = {foo: "bar"};
var x = "foo";
data[x]; //=> bar

var y = "hello";
data[y] = "panda";
data["hello"]; //=> panda

I think this is a little cleaner and self-contained than the window approach

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.