Home > front end >  Declare variable name dynamically in javascript
Declare variable name dynamically in javascript

Time:02-10

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 = "";

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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;
}
  •  Tags:  
  • Related