Variable Variables in Javascript
Today I was looking for a decent way to have variable variables in Javascript. Because I work with a whole bunch of particularly bright people*, the answer to any question is always near. I figured I'd share today's little insight! First let's look about how we'd do this in PHP:
Suppose you have a variable named $i containing a numeric value. In this example it's 1 but it could be anything. You want to create a new variable named name1. In PHP you'd use the double $ way:
$i=1;${'name'.$i} = 'Marco';echo "got ".$name1;
When doing the same thing in Javascript, the dreaded eval() comes to mind:
var i=1;eval('name' + i + ' = "Marco"');document.write('got ' + name1);
Nasty. We don't want to use eval() if we can avoid it. And most of the time we actually can! Here's a much more proper way of doing it, using the fact that all global variables are held in the window array.
var i=1;window['name' + i] = 'Marco';document.write('got ' + name1);
There we go! Nice, clean and no eval() necessary.
* It's absolutely delightful to work with people who all excel in what they do without the often associated 'arrogant prick attitude'. I love my job! =)
Filed under: reads
Number of comments:
Number of trackbacks:
Tagged with: 







At 14 June '07 - 09:30 Dave O'Brien wrote:
var i=1;
window[‘name’ + i] = ‘Marco’;
document.write(‘got ‘ + name1);
But can you tell me why this is more useful than just accessing array members? At least then you can control scope.
At 14 June '07 - 09:32 Dave O'Brien wrote:
At 14 June '07 - 11:01 Marco wrote:
And.. you’re right. Fixed it. About the other thing: The purpose of this post was that it’s better than using eval.
Lesson learned today: Don’t quickly make posts during lunch breaks. Thanks for reminding me of that
At 14 June '07 - 16:05 Mi wrote:
->We don’t want to use eval() if we can avoid it.
Can you explain why?
At 14 June '07 - 16:43 Marco wrote:
Because eval is very inefficient. It shouldn’t be used really unless there’s really no other way to achieve what you want.
At 16 June '07 - 09:06 giku wrote:
I’m not sure what are you writting about here.
About dynamic variable creation ?
It’s nothing exploratory for someone who KNOWS JS.
1. Remember, that every object (also scope) in ECMA (js) is a hashmap.
So you can:
this[‘myvar’] = 1
window[‘myvar’] = 2
myobject[‘myvar’] = 3
and access it like: this.myvar, window.myvar, myobject.myvar
2. There is a little bit incomprehensible:
eval(‘name’ i ‘ = “Marco”’) is something completely different than
window(‘name’ i)
why ? The basics again: the scope is different… first scope is local , second is window.
Difference is very significiant.
Well, it’s just a basic knowledge.
At 16 June '07 - 09:07 leptonix wrote:
At 16 June '07 - 11:40 Dave O'Brien wrote:
About your second point. I’m pretty sure you’re wrong. Variables declared without var are in global scope, not local do where they were declared, and window.variable_name / window[“variable_name”] is in global scope, too, or if that’s not exactly correct then perhaps I should say they’re available throughout the document. If he’d written:
eval(‘var name’ i ‘ = “Marco”’);
then you’d‘ve had a point. That’s the sole reason I only mentioned window instead of going into objects as associative arrays in ECMAScript.
Try having two functions, one which sets the variables and one which tries to read their values. You’ll find if you eval with var then the second function will give you “variable undefined” or similar, but without it the variable value is available. Same with window[“variable_name”]. You can just call, for example, alert(variable_name); in the second function and it can read it, without having to prepend window. Hence it and Marco’s eval statement achieve the same thing.
At 16 June '07 - 12:04 Marco wrote:
At 21 September '07 - 02:36 Sunil wrote:
At 30 March '08 - 07:39 Philofax wrote:
Oh so happy…....lalalalala
If you think my slideshow script is helpful, of you can improve if for me, please drop me a line.
At 08 May '08 - 13:23 Nate wrote:
At 11 May '08 - 11:44 Gustavo wrote:
At 20 May '08 - 15:15 jbrown wrote:
At 14 June '08 - 11:04 John A. Bilicki III wrote:
At 10 September '08 - 14:19 Geomagnet wrote:
$a=“Marco”;
$$a=1;
Now $Marco=1
I’ve seen someone use $$a in javascript but can’t be sure this is the same. Honestly, I think I’ve missed the boat. Can someone provide an
example of where this saves time, expands functionality, reduces code, or any other benefit? Some of the code I have to fix has these datatypes thrown around with no rhyme or reason. It’s as if the programmer is so smart he has to make the job too cryptic for anyone else to understand.
Thanks
At 12 May '09 - 01:11 Dan wrote:
it shows how you can make a dynamic form, then you could use variable variables to give each form input a different id, so that php could grab it after you hit submit:
var id = 0;
function removeElement(divNum) {
var d = document.getElementById(‘l’);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
function removeElementl(divNum) {
var d = document.getElementById(‘l’);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
function writestuff() {
id = 1;
var stuff = document.createElement([‘p_’ id]);
stuff.setAttribute(‘id’, [‘p_’ id]);
stuff.appendChild(document.createTextNode([‘hello ‘ id]));
document.getElementById(‘l’).appendChild(stuff);
var killbutton = document.createElement(‘input’);
killbutton.value = “X”;
var n = id;
function f() {removeElementl([‘p_’ n]);} killbutton.onclick = f;
killbutton.type = “button”;
stuff.appendChild(killbutton);
stuff.appendChild(document.createElement(‘br’));
}
At 12 May '09 - 20:31 Dan wrote:
in this particular example, you’re just getting a list of options… the php code here would render this function:
function createInputOriginCountry(id) {
return “origin country: PEOPLES REP OF CHINAAFGHANISTANALBANIAALGERIAANGOLAARGENTINAAUSTRALIAAUSTRIAAZORESBAHAMASBAHRAINBANGLADESHBARBADOSBELGIUMBELIZEBENINBERMUDABOLIVIABOTSWANABRAZILBRITISH PACIFIC ISBRUNEIBULGARIABURMABURUNDICAMBODIACAMEROONCANADACANARY ISLANDSCAYMAN ISLANDSCENTRAL AFRICAN REP.CHADCHILECOLOMBIACOMOROSCONGO (BRAZZIVILLE)COSTA RICACUBACYPRUSCZECHOSLOVAKIADENMARKDJIBOUTIDOMINICAN REPUBLICEAST COASTECUADOREGYPTEL SALVADOREQUATORIAL GUINEAESTONIAETHIOPIAFALKLAND ISLANDSFINLANDFRANCEFRENCH GUIANAFRENCH INDIAN OCEANFRENCH PACIFIC ISFRENCH WEST INDIESGABONGEORGIAGERMANYGHANAGIBRALTARGREECEGREENLANDGUATEMALAGUINEAGulf CoastGUYANAHAITIHONDURASHONG KONGHUNGARYICELANDINDIAINDONESIAIRANIRAQIRELANDISRAELITALYIVORY COASTJAMAICAJAPANJORDANKENYAKUWAITLAOSLATVIALEBANONLEEWARD AND WINDWARDLIBERIALIBYALITHUANIAMACAUMADEIRA ISLANDSMALAGASY REPUBLICMALAYSIAMALIMALTA AND GOZOMAURITANIAMAURITIUSMEXICOMONGOLIAMOROCCOMOZAMBIQUENAMIBIANEPALNETHERLANDSNETHERLANDS ANTILLESNEW ZEALANDNICARAGUANIGERIANORTH KOREANORWAYOMANOTHER PACIFIC IS NECPAKISTANPANAMAPAPUA NEW GUINEAPARAGUAYPERUPHILIPPINESPOLANDPORTUGALQATARREP. OF SOUTH AFRICAREPUBLIC OF CHINAREPUBLIC OF KOREAROMANIARUSSIASAUDI ARABIASENEGALSIERRA LEONESINGAPORESOUTHERN ASIA N.E.CSPAINSPANISH AFRICA NECSRI LANKA (CEYLON)ST. HELENASUDANSURINAMSWEDENSWITZERLANDSYRIAT PAC ITANZANIATHAILANDTHE GAMBIATOGOTRINIDAD AND TOBAGOTUNISIATURKEYTURKS AND CAICOS ISUGANDAUNITED ARAB EMIRATESUNITED KINGDOMUPPER VOLTAURUGUAYVENEZUELAVIETNAMWest CoastWESTERN AFRICA NECWESTERN SAHARAWESTERN SAMOAYEMENYUGOSLAVIAZAIREZAMBIA”;
}
so you can delete the php and throw that up instead if you want to see this demonstrated:
var id = 0;
var InputOriginCountry = 0;
At 20 May '09 - 05:54 Lauxa wrote:
At 27 June '09 - 09:05 Roberto Aguilar wrote:
Last night i was developing this application in Flash Media Server, and the server-side code (for the ones that doesnt use it), is totally javascript, so i had to create this object that contained 48 properties, why not to use a simple array?, cause that object was my array, and i needed 8 instances of that object. So my approach was something like this.
function draft()
{
this.ejm0 = “”;
this.ejm1 = “”;
this.ejm2 = “”;
this.ejm3 = “”;
this.ejm4 = “”;
this.ejm5 = “”;
this.ejm6 = “”;
this.ejm7 = “”;
this.ejm8 = “”;
this.ejm9 = “”;
this.ejm10 = “”;
this.ejm11 = “”;
}
It would have been simpliear to just write a loop defining:
while(i = 0; i < 12; i )
{
this[“ejm” i];
this[“eje” i];
this[“sjm” i];
this[“pos” i];
}
It was a draft for a baseball team, and they was unsure about the number of fields there should be. So it would be easiear to just modify the number of iterations of the loop. Unfortunately i was in a rush and ended up with 48 lines defining the properties of the object. It worked just fine since it was a tiny project for a one time use.
So bottom line, this is a cool feature if youre in need to define random amounts of variables wich are named secuentially.
At 13 July '09 - 03:21 zerokilled wrote:
i hate tutorial that confuse JS begginer when it come to array. when the tutorial explain how array are created, some mention that there is another “cool” way of creating elements in the array. what i’m talking is the form of
var myArray = [];
myArray[‘john’] = 29;
myArray[‘peter’] = 18;
in fact, myArray have 0 elements despite the last two statements. what is truly doing is creating new properties for the object.