6

Possible Duplicate:
Javascript dynamic variable name

A very basic question. I want to create a new javascript global variable each time a function is called. The variable should contain the id of the element so that I can easily access it later.

id = 2347

//this function would be called multiple times, hopefully generating a new global each time
function (id)
{
var + id = something
// I want a variable that would be named var2347 that equals something, but the above line doesn't get it.
}

In a later function, I want to access the variable like so:

function two (id)
{
alert(var + id);
}

I'm sure I'm going to have a "doh!" moment when someone is kind enough to answer this.

4
  • Do you want a new global variable or just an existing global variable id to have a new value ? Commented Dec 25, 2011 at 15:18
  • You want to avoid global variables. Create your own namespace instead... Commented Dec 25, 2011 at 15:24
  • Just make it an array and write vars[12345] instead of vars12345. Commented Dec 25, 2011 at 15:49
  • Thanks to all of you for these great answers! Commented Dec 25, 2011 at 20:15

4 Answers 4

7

How about...

var store = (function() {
    var map = {};

    return {
        set: function ( name, value ) {
            map[ name ] = value;
        },
        get: function ( name ) {
            return map[ name ];
        }
    };
})();

Usage:

store.set( 123, 'some value' );

and then...

store.get( 123 ) // 'some value'
store.get( 456 ) // undefined

Live demo: http://jsfiddle.net/jZfft/

Programmers are highly advised to not declare global variables, since the browsers already ship with several hundreds of names in the global namespace. Using the global namespace for your own variables can lead to name-collisions which can then break the program or some of the browser's functionality. Creating new namespaces is free, so don't be shy to do it...

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the last paragraph, but I do think this solution is a bit overkill. Instead of a global map variable you're creating a global store variable. The mere thing this adds is some syntactic sugar in my opinion.
@pimvdb Yea, it is kind-of an overkill. This is the most basic form of this pattern. It becomes more useful when the get/set behavior is more complex (when multiple commands have to be executed)...
4

Global variables are properties of the window object, so window.lol and window['lol'] define a global variable lol which can be accessed in any of these ways. The second, window['lol'], can also be used with variable names, like this:

var lol = 123;
var name = 'lol';
var content = window[name]; // window['lol'] == 123

content will now contain 123. Pretty much anything can be put between square brackets [], so you can also do this:

var id = 123;
window['prefix' + id] = 'text';
var content = window['prefix' + id]; // prefix123 == text

Or, in your case:

var id = 2347;
function one(id) {
  window['var' + id] = something;
}
function two(id) {
  alert(window['var' + id]);
}

2 Comments

I believe this is only true for some JS implementations (like those in a browser but not Node.JS for example, there's no window there).
Oh yes, I forgot about Node and such :(. I think node uses global instead of window, don't know about the others... well you could go middle finger to coding standards and eval x].
3

You can save your values to the global hash:

var g = {};

function (id)
{
  g[id] = something;
}

function two (id)
{
  alert(g[id]);
}

Comments

3

I would argue that you don't really want to be making lots of global variables. Rather, you can just make one global object or array and attach all your other variables to that. In this case, you probably want an object:

var myIds = {};

function makeSomething(id) {
    // create something that goes with this id
    myIds[id] = something;
}

Then, to fetch that information at some time later, you can retrieve it with this:

var something = myIds[id];

The reason for this suggestion is many-fold. First off, you want to minimize the number of global variables because every global is a chance for a naming collision with some other script you might be using. Second off, when keeping track of a bunch of related data, it's a better programming practice to keep it in one specific data structure rather than just throw it all in the giant global bin with all other data.

It's even possible to create an object that manages all this for you:

function idFactory() {
    this.ids = {};
}
idFactory.prototype = {
    makeSomething: function(id) {
        // create something that goes with this id
        this.ids[id] = something;
    },
    retrieveSomething: function(id) {
        return(this.ids[id]);
    },
    clear: function() {
        this.ids = {};
    } 
};

// then you would use it like this:
var myIds = new idFactory();
myIds.makeSomething(2347);
var value = myIds.retrieveSomething(2347);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.