Can we create dynamic variable in javascript?

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

Can we create dynamic variable in javascript?

asked Nov 24, 2011 at 16:36

2

Use an array for this.

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

Can we create dynamic variable in javascript?

hichris123

9,99515 gold badges55 silver badges68 bronze badges

answered Nov 24, 2011 at 16:38

8

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.

answered Nov 24, 2011 at 16:40

Todd DitchendorfTodd Ditchendorf

11k14 gold badges66 silver badges120 bronze badges

7

Try this

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

Can we create dynamic variable in javascript?

Pratik Butani

57.9k55 gold badges258 silver badges420 bronze badges

answered May 20, 2013 at 20:47

SafiqSafiq

2192 silver badges2 bronze badges

1

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

answered Apr 20, 2017 at 5:51

3

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

answered Apr 20, 2018 at 14:53

Can we create dynamic variable in javascript?

1

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

answered Feb 9, 2021 at 11:38

nano devnano dev

2854 silver badges6 bronze badges

var marker  = [];
for ( var i = 0; i < 6; i++) {               
     marker[i]='Hello'+i;                    
}
console.log(marker);
alert(marker);

Can we create dynamic variable in javascript?

Smit Patel

2,8031 gold badge20 silver badges44 bronze badges

answered Nov 11, 2019 at 10:21

Can we create dynamic variable in javascript?

2

 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.

answered Nov 24, 2012 at 6:52

AlfgaarAlfgaar

1721 silver badge7 bronze badges

1

Are JavaScript variables dynamic?

Dynamic variables are rarely used in JavaScript. But in some cases they are useful. Unlike PHP, there is no special implementation of dynamic variable names in JavaScript. But similar results can be achieved by using some other methods.

What is a dynamic value in JS?

Dynamic values are the values we assign to the dynamic variables. A dynamic variable is a type of variable that doesn't have any specific name in the code through hard coded, its address is determined when the code is running. The name dynamic refers to the value which is capable of action and change.

What is a dynamic variable?

Dynamic variables compute their own values by executing statements and logical expressions. A dynamic variable assigns itself the result of a calculation or operation. The dynamic variable types are dynamic string, dynamic number, and dynamic True/False (Boolean).

How do you create a variable in JavaScript?

To create a variable in JavaScript, use the let keyword. To be concise, we can combine the variable declaration and assignment into a single line: let message = 'Hello!'; // define the variable and assign the value alert(message); // Hello!