97

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

2
  • 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? Commented Nov 24, 2011 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. Commented Nov 24, 2011 at 16:48

9 Answers 9

136

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}
Sign up to request clarification or add additional context in comments.

8 Comments

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?
What if I want to use destination[1]address, destination[1]description, destination[1]name?
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.
@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.
@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.
|
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.

7 Comments

Why break out of the scope and throw it on the window??? That's just begging for problems later on.
Ya- it will work- just selecting a value later can be problematic.
Needed this one and got it here. Sometimes knowing a different path is good.
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!
"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).
|
23

Try this

window['marker'+i] = "some stuff"; 

1 Comment

Thanks for answering the question. Of course everyone knows an array is better, but SOMETIMES, you need to do something unorthodox.
19

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]  */
}

3 Comments

this is a pure solution for dynamic variable
The only solution here that worked properly for my needs. Much better than the accepted answer of "use an array". Thanks!
I use it in function to call another function from the superfunction's parameter name: function wildname(evenwilder){eval(evenwilder)(wild1)}
2

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);
}

2 Comments

You use both here, eval and array.
@Timo what array? didn't use array.
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();

Comments

0

Using ES6 method. No array needed

for (let i = 1; i < coords.length; i++){
 eval(`var marker${i} = 'some stuff';`);
}

3 Comments

Using eval for this purpose is a bad idea. It in the best case prevents minification and in the worst case results in broken code when minification is used, you will also have problems with linting, and is also bad for maintaining code.
Good point, now do suggest the solution
There are already plenty of valid solutions in this and the other question here on SO, there is no need to suggest the same solutions once again.
-3
var marker  = [];
for ( var i = 0; i < 6; i++) {               
     marker[i]='Hello'+i;                    
}
console.log(marker);
alert(marker);

2 Comments

Please, consider adding a brief explanation to your answer so that the question author can better understand what you did
And explain the difference with previous answers
-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.

1 Comment

Hamid, he explains why it doesn't work, this is not supposed to be a working solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.