92

I'm working on an ajax google maps script and I need to create dynamic variable names in a for loop.

for (var i = 0; i < coords.length; ++i) {
    var marker+i = "some stuff";
}

What I want to get is: marker0, marker1, marker2 and so on. and I guess there is something wrong with marker+i

Firebug gives me this: missing ; before statement

Luke Peterson
  • 8,584
  • 8
  • 45
  • 46
Philipp Bergmann
  • 973
  • 1
  • 9
  • 11
  • 2
    I think you need to give a bit more context for a better answer. What do you mean by "count up var names"? Is marker defined somewhere outside the loop? – Zut Nov 24 '11 at 16:42
  • 3
    Ya - If you search for Javascript Arrays you will get your answers,tutorials- Sometimes its just difficult to name what you want. Fair enough. – Piotr Kula Nov 24 '11 at 16:48

8 Answers8

131

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}
hichris123
  • 10,145
  • 15
  • 56
  • 70
JohnP
  • 49,507
  • 13
  • 108
  • 140
  • This was edited from coords.length to markers.length -- was approved before I could reject. I think that edit is wrong -- why would you loop through an empty object? – Chris Wilson Jul 09 '14 at 18:31
  • You're agree! Sorry 4 my mistake! – T30 Jul 09 '14 at 18:33
  • 2
    What if I want to use destination[1]address, destination[1]description, destination[1]name? – Pitto Sep 16 '15 at 14:34
  • 13
    This doesn't answer the question. These kind of answers are a pain to see when you come here from a google search looking for a solution to a problem. I think we need to stop doing this, as a community. – Edward D'Souza Nov 07 '17 at 20:11
  • @EdwardD'Souza This is quite an old answer. Not sure what you mean that it doesn't answer the question. The answer is what the OP was looking for (hence the green tick). If you tell me what was lacking I might be able to expand on it. – JohnP Nov 09 '17 at 12:43
  • 2
    @JohnP It doesn't answer the question as written in the title ("how do I create dynamic variables"). Fair enough that it was marked as the answer. It is just frustrating when you're using Google to find answers and the top answer is not what you expect. – Edward D'Souza Nov 09 '17 at 16:26
  • 4
    @EdwardD'Souza The answer is exactly related to the question. The OP is asking about how to create a set of variables and be able to refer to it later without knowing how many variables are needed. The answer shows how you create these values in an array and not pollute the global scope. – JohnP Nov 09 '17 at 21:27
  • 'Coming in from a Google search also. (That makes me a Google-raptor?) I actually appreciate JohnP's answer because it gives me an idea of best practice. For my very limited need, I'll first try using Todd Ditchendorf's scoping properties approach below, but will keep in mind the advantages of using an array. – PatrickReagan Mar 14 '19 at 19:32
60

I agree it is generally preferable to use an Array for this.

However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this – which always refers to the current scope.

for (var i = 0; i < coords.length; ++i) {
    this["marker"+i] = "some stuff";
}

You can later retrieve the stored values (if you are within the same scope as when they were set):

var foo = this.marker0;
console.log(foo); // "some stuff"

This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.

Todd Ditchendorf
  • 11,217
  • 14
  • 69
  • 123
  • 6
    Why break out of the scope and throw it on the window??? That's just begging for problems later on. – Andrew Nov 24 '11 at 16:43
  • 2
    Ya- it will work- just selecting a value later can be problematic. – Piotr Kula Nov 24 '11 at 16:50
  • Maybe. I can imagine a situation where you might actually need this. However, it's unclear whether the questioner has a legitimate need for this or realizes this is generally a bad idea. – Todd Ditchendorf Nov 24 '11 at 17:07
  • 1
    @shyamnathan: Use `this['marker1']` or `this.marker1`. Or, if this is at the top-level scope, you can use `window['marker1']` or `window.marker1`. – Todd Ditchendorf Jul 02 '14 at 23:27
  • 4
    Needed this one and got it here. Sometimes knowing a different path is good. – ni8mr Jun 07 '16 at 07:18
  • 3
    This solution helped me. In my case "some stuff" is an array, so I was looking for solution without nesting arrays (just because it is easier to maintain). Thanks a lot! – jazzgot Jul 16 '16 at 10:54
  • 3
    "*using this – which always refers to the current scope*". No it doesn't. *this* has nothing to do with scope, it's a parameter of an execution context that is set by the call, or *bind*, and may be a different value on each call of a function. It may be *undefined* in strict mode (though strict mode was introduced with ECMA-262 ed 5 in June, 2011). – RobG Jan 27 '17 at 21:29
22

Try this

window['marker'+i] = "some stuff"; 
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Safiq
  • 229
  • 2
  • 2
  • 1
    Thanks for answering the question. Of course everyone knows an array is better, but SOMETIMES, you need to do something unorthodox. – deps_stats Jun 10 '20 at 21:59
16

In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval() is even another option.

v0 = "Variable Naught";
v1 = "Variable One";

for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
  dyV = eval(`v${i}`);
  console.log(`v${i}`); /* => v0;   v1;  */      
  console.log(dyV);  /* => Variable Naught; Variable One;  */
}

When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval() to get the value is kind of lame when you're used to getting it automatically.

_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}]    //Array of Object(s)


for (i = 0; i < 3; i++)
{
  console.log(`_${i}`);           /*  var
                                   * =>   _0  _1  _2  */

  console.log(`"_${i}"`);         /*  var name in string  
                                   * => "_0"  "_1"  "_2"  */

  console.log(`_${i}` + `_${i}`); /*  concat var with var
                                   * => _0_0  _1_1  _2_2  */

  console.log(eval(`_${i}`));     /*  eval(var)
                                   * => My first variable
                                        Object {key_0: "value_0"}
                                        [Object]  */
}
kayleeFrye_onDeck
  • 6,648
  • 5
  • 69
  • 80
  • 2
    this is a pure solution for dynamic variable – webdevanuj Sep 03 '20 at 11:48
  • 2
    The only solution here that worked properly for my needs. Much better than the accepted answer of "use an array". Thanks! – Partack May 07 '21 at 21:09
  • 1
    I use it in function to call another function from the superfunction's parameter name: `function wildname(evenwilder){eval(evenwilder)(wild1)}` – Timo Jun 02 '22 at 07:48
1

You can use eval() method to declare dynamic variables. But better to use an Array.

for (var i = 0; i < coords.length; ++i) {
    var str ="marker"+ i+" = undefined";
    eval(str);
}
Md Junaid Alam
  • 1,131
  • 13
  • 20
0

In this dynamicVar, I am creating dynamic variable "ele[i]" in which I will put value/elements of "arr" according to index. ele is blank at initial stage, so we will copy the elements of "arr" in array "ele".

function dynamicVar(){
            var arr = ['a','b','c'];
            var ele = [];
            for (var i = 0; i < arr.length; ++i) {
                ele[i] = arr[i];
 ]               console.log(ele[i]);
            }
        }
        
        dynamicVar();
nano dev
  • 335
  • 4
  • 6
-3
var marker  = [];
for ( var i = 0; i < 6; i++) {               
     marker[i]='Hello'+i;                    
}
console.log(marker);
alert(marker);
Smit Patel
  • 2,992
  • 1
  • 26
  • 44
-7
 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

Alfgaar
  • 172
  • 1
  • 7