Variable name for a variable in JavaScript

We use the following syntax to declare a variable with a particular name in JavaScript:

var1=10;

This will assign the value 10 to var1.

But there are situations when you would like to use a name of the variable that would come rather programmatically(dynamically). To facilitate variable(dynamic) name of a variable you may use the following structure of code.

var1="var2";// In place of "var2" there may be random code that must return a string(that will be treated as the variable name you need dynamically).
window[var1]=10;
alert(var2);// alerts 10;

So here var2 may come programmatically which you may not know. In many real time web applications you may come across such a situation when you need this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s