Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 21

Declare variable name dynamically in javascript

In JavaScript I want to make a function which takes an argument and in this function a variable will be created whose name will be the value of the argument.
For example if user pass "jack" in the argument then in function I want a variable whose name is jack like:

var jack = "";

Upvotes: 1

Views: 1516

Answers (5)

Guido Bouman
Guido Bouman

Reputation: 3275

To prevent using the window global array, you can create a local array which holds your variables.

function doSomething(var) {
  var vars = {};
  vars[var] = value;
}

Upvotes: 0

Alberto De Caro
Alberto De Caro

Reputation: 5213

You could always use a dictionary. Here is a very simple stub:

function Dictionary(){
    var container = {};

    this.set = function(key, value){
        container[key]  = value;
    }

    this.get = function(key){
        return container[key];
    }
}

var vars = new Dictionary();
vars.set('foo', 'foo rocks');
vars.set('bar', 'bar rocks too');

console.log(vars.get('foo'));
console.log(vars.get('bar'));

Upvotes: 0

spaceman12
spaceman12

Reputation: 1109

The best that you can do about is to create an object and assigns the variable name to the keys of the created object like this -

var myvar={};
function create(var){
    myvar[var]='values';
}

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173562

Creating local variables via a function is typically a bad idea. You could accomplish something similar by passing a local object around, e.g.

function setVar(o, name, value)
{
    o[name] = value;
}

Then, inside your local scope:

var o = {};

setVar(o, 'jack', 123);

// o.jack contains 123

In this way, if the need would really arise (this is rarely required) to introduce global variables in this manner, you can always call the function like this:

setVar(window, 'jack', 123);
// now window.jack == jack == 123

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Typically, you won't need to do this. As Bergi pointed out, a local variable would usually suffice. However, in the event that you do need to use this technique, you could give the property to the window object:

function setVariable(userPassedString);
    window[userPassedString] = "";
}

Don't use eval for this, ever, no matter how tempted you are to.

Upvotes: 1

Related Questions