Spiga

Javascript ‘Variable’ Variables

by Gabi Solomon

If you havent figure it out by now, my "expertise" is more on the back-end ( php & mysql ) than with front end. So i sometimes look for solutions in javascript that i know how to do in php.

One of this is the concept of variable variables. A ‘variable’ variable is when the identifier of a variable is a variable itself. To be more specific, this works by taking a string as the name, and then defining a variable with that name. That variable can then be used as a normal variable.

The solution in Javascript

1. Using Eval
the first solution i found was to use eval.

JAVASCRIPT:
  1. var x='street';
  2. eval('name_' + x + ' = "Lincon Road"');
  3. document.write('got ' + name_street);

This should result in having a variable name_street with the value Lincon Road.

However from my small knowledge of JS, i have come to understand that you should avoid using eval when possible.
2. Better Solution - Using Window Array

JAVASCRIPT:
  1. var x='street';
  2. window['name_' + x] = 'Lincon Road';
  3. document.write('got ' + name_street);

Same effect, with no eval :D

This is all for today,
cheers

Related Posts

  • http://www.vibramshoesonline.com vibram fivefingers

    Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
    air jordan 16.5
    If its common it might be difficult to get, however, be creative and you can usually find something.