Javascript create variable from its name

try:

this[name] = "value";

All objects can use dot and array notation for variable access.

Also note, this will allow you to create name value pairs that are inaccessible via dot notation:

var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine

If you are creating a new object literal, you can use string literals for the names for values with special characters:

var foo  = {'bar-baz':'fizzbuzz'};

But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:

var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'

Because other answerers are mentioning eval, I will explain a case where eval could be useful.

Warning! Code using eval is evil, proceed with caution.

If you need to use a variable with a dynamic name, and that variable does not exist on another object.

It’s important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.

If you need a dynamic variable name within a closure it is better to use a container object:

var container = {};
container[foo] = 'bar';

So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.

var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );

Leave a Comment