324

I’ve looked for solutions, but couldn’t find any that work.

I have a variable called onlyVideo.

"onlyVideo" the string gets passed into a function. I want to set the variable onlyVideo inside the function as something. How can I do that?

(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if statements.)

Edit: There’s probably a better way of doing what you’re attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.

A simple intro:

// create JavaScript object
var obj = { "key1": 1 };

// assign - set "key2" to 2
obj.key2 = 2;

// read values
obj.key1 === 1;
obj.key2 === 2;

// read values with a string, same result as above
// but works with special characters and spaces
// and of course variables
obj["key1"] === 1;
obj["key2"] === 2;

// read with a variable
var key1Str = "key1";
obj[key1Str] === 1;
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
switz
  • 24,384
  • 25
  • 76
  • 101
  • 6
    What are you using this for? Are you absolutely sure you need to set it to a normal local variable, and an Object (Hash) won't work? – Dogbert Apr 10 '11 at 18:32
  • mmm... I still don't quite grasp why you want to do this in a world with arrays. Anyway, some of your code and explanation would help a lot. – Kevin Chavez Apr 10 '11 at 18:34
  • i think we need more detail about what your ultimate goal is – mcgrailm Apr 10 '11 at 18:35

12 Answers12

343

If it's a global variable then window[variableName] or in your case window["onlyVideo"] should do the trick.

yckart
  • 32,460
  • 9
  • 122
  • 129
ingo
  • 5,469
  • 1
  • 24
  • 19
  • 50
    Even if not global, you can access it like that by `scope[property]` or even `this[property]` – Wojciech Bednarski Jul 22 '14 at 21:38
  • 13
    @WojciechBednarski: Don't confuse scope and context. `this` is context, what it points to depends on how the function is called. In JS, 50% of the time `this` is `window` unless you enable strict mode and `this` becomes `undefined` and will throw an error. Scope is something completely different and it's not an object (except global scope which is mirrored by the `window` object) – slebetman Jun 26 '15 at 03:00
  • 3
    Doesn't work in `WebWorkers` (where `self` reffers to global scope, just as it does in browser, where it's equal to `window`) and Node.js, where `global` is the variable you want. And it newer works with local scopes, such as the function body. – Tomáš Zato Oct 11 '15 at 23:00
  • 1
    is there anyway to define a `const` using this method? – toing_toing Mar 04 '19 at 21:16
  • 2
    What if the variable was create using let and const? It won't be a part of global scope. – Sameer Reza Khan Dec 05 '20 at 07:18
  • If one was testing global variables, then shouldn't `globalThis` be used instead (being more universal)? – polendina Sep 12 '22 at 09:43
221

Javascript has an eval() function for such occasions:

function (varString) {
  var myVar = eval(varString);
  // .....
}

Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need

function SetTo5(varString) {
  var newValue = 5;
  eval(varString + " = " + newValue);
}

or if using a string:

function SetToString(varString) {
  var newValue = "string";
  eval(varString + " = " + "'" + newValue + "'");
}

But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()

Community
  • 1
  • 1
goggin13
  • 7,876
  • 7
  • 29
  • 44
  • 4
    Yeah I would go with this rather then using window ( it has some caveats) – ingo Apr 10 '11 at 18:36
  • 13
    Why was one `eval()` answer downvoted to deletion, and this one upvoted? – BoltClock Apr 10 '11 at 18:41
  • 1
    @BoltClock: good question. Also, I think I rushed and misread the question, I'm not sure my answer really helps the OP. I added an edit which I think does what @Switz wants, but I also agree with the comments on the question, there's probably a much more appropriate way to accomplish this – goggin13 Apr 10 '11 at 18:43
  • 5
    @goggin You should regex-test the argument to make sure that it's a valid name. Just evaling the argument without checking it first is ridiculously insecure. – Šime Vidas Apr 10 '11 at 18:54
  • 21
    This is the only realistic answer to the question. Just because it involved the "eeeeevil" eval does not make it any less true. Javascript does not have variable variables (such as $$varname in php) so this really is the only answer. Using `window[varname]` has the side-effect of introducing global variables, which might not be wanted. @Shaz I don't think you give modern JS interpreters enough credit. They are *extremely* fast, and parsing and executing a simple one line assignment operation is not going to spike anyone's CPU usage as long as it is not being done in a 1ms timer or tight loop. – MooGoo Apr 10 '11 at 19:04
  • Summary: eval is evil Details: the window['variableName'] method ONLY works if the variable is defined in the global scope. I've seen a ton of these. The correct answer is "Refactor". – Lance Caraccioli Mar 29 '14 at 09:20
  • 2
    @TheParamagneticCroissant People who are passionate about code care. Those who only value time and money don't. – Jimbo Feb 23 '15 at 12:54
  • I'm so confused about this. I'm accustomed to working in autohotkey where I can make variables out strings very easily. Can you show me another example of how to use this to create a variable from a joined string and then assign it a value? – bgmCoder Dec 19 '15 at 04:52
  • In my mind, I want to do this: `var s="foo"; var t="bar"; var eval(s+t)="dude"; console.log(foobar);` which should print *dude*, being the value of the new variable, `foobar`. – bgmCoder Dec 19 '15 at 05:01
  • @bgmCoder `var s="foo"; var t="bar"; eval("var " + s + t + "='dude';");console.log(foobar);` – Valen Jun 04 '17 at 15:47
  • @Jimbo "People who are passionate about code care. Those who only value time and money don't." As someone who works in security this is a huge misconception. If you really valued time and money, you would limit/eliminate your use of eval so you don't have to shell out money to fix security holes, notify your customers about how you leaked all their data, deal with legal implications, etc. If you do end up using eval in production code, make absolutely sure the content isn't attacker controlled. If it is too difficult to check this, then don't use eval. – Allen Nov 15 '20 at 15:04
  • @Allen The person I was replying to removed their comment. You have no idea of the context of that conversation. And neither do I, lol. Unnecessary comment here. – Jimbo Nov 15 '20 at 15:07
54

As far as eval vs. global variable solutions...

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

var tempNamespace = {};
var myString = "myVarProperty";

tempNamespace[myString] = 5;

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

jm0
  • 3,294
  • 2
  • 16
  • 18
  • A bit refactor your code to make the same inline var tempNamespace = {["myVarProperty"]: "Definitely only video"}; – Tioma Feb 15 '17 at 12:50
  • 1
    This is a very good solution - it seems like eval() is to be avoided unless absolutely necessary, very elegant workaround here. – skwidbreth Feb 27 '17 at 17:58
  • Starting with the collection document.body.getElementsByTagName('*') it is easy to find all the elements having an 'id' attribute and create a variable for the element object value of each one in a global object 'id'. Then you can refer to
    in JavaScript as 'id.container'. So easy!
    – David Spector Nov 24 '18 at 19:09
22
var myString = "echoHello";

window[myString] = function() {
    alert("Hello!");
}

echoHello();

Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/

RAGINROSE
  • 694
  • 8
  • 13
Shaz
  • 15,637
  • 3
  • 41
  • 59
10

You can do like this

var name = "foo";
var value = "Hello foos";
eval("var "+name+" = '"+value+"';");
alert(foo);
9

You can access the window object as an associative array and set it that way

window["onlyVideo"] = "TEST";
document.write(onlyVideo);
Eric Conner
  • 10,422
  • 6
  • 51
  • 67
7

The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.

(function(){
    var findMe = 'no way';
})();
Lance Caraccioli
  • 1,421
  • 13
  • 14
7

If you're trying to access the property of an object, you have to start with the scope of window and go through each property of the object until you get to the one you want. Assuming that a.b.c has been defined somewhere else in the script, you can use the following:

var values = window;
var str = 'a.b.c'.values.split('.');

for(var i=0; i < str.length; i++)
    values = values[str[i]];

This will work for getting the property of any object, no matter how deep it is.

  • Your example is cool. I note that if I use `name` as the variable name, your example fails, but it works with other variable names. This may have to do with the Window object already having a `name` variable. Also, including the `.value` method caused failure. The ability to interpret deeply nested object variables is what I am looking for and your method indicates a good direction. Thanks. – Theo Jul 31 '16 at 19:23
  • No problem. The answer is more to demonstrate the concept rather than be a copy/paste answer (as are most answers here on SO I think) –  Aug 02 '16 at 07:27
  • 1
    SO responses are even better when you can spend the time improving them rather than fixing them. ;-) – Theo Aug 04 '16 at 05:36
  • Doesn't work: `Uncaught TypeError: Cannot read property 'split' of undefined` – Roberto14 Apr 26 '18 at 15:15
0

It can be done like this

(function(X, Y) {
  
  // X is the local name of the 'class'
  // Doo is default value if param X is empty
  var X = (typeof X == 'string') ? X: 'Doo';
  var Y = (typeof Y == 'string') ? Y: 'doo';
  
  // this refers to the local X defined above
  this[X] = function(doo) {
    // object variable
    this.doo = doo || 'doo it';
  }
  // prototypal inheritance for methods
  // defined by another
  this[X].prototype[Y] = function() {
    return this.doo || 'doo';
  };
  
  // make X global
  window[X] = this[X];
}('Dooa', 'dooa')); // give the names here

// test
doo = new Dooa('abc');
doo2 = new Dooa('def');
console.log(doo.dooa());
console.log(doo2.dooa());
yunzen
  • 32,854
  • 11
  • 73
  • 106
0

The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.

// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
    {
    thisid = els[i].id;
    if (!thisid)
        continue;
    val=D.getElementById(thisid);
    id[thisid]=val;
    }

// Usage:
id.MyDIV.innerHTML="hello";
David Spector
  • 1,520
  • 15
  • 21
0

Here, Short and Sweet If You Want to convert your answer into variable

 const container = "foo"

// if you want foo as varible

   eval(container)  

according 2023 Javascript

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 28 '23 at 03:23
  • There are way better existing answers on how to use `eval` for this. – gre_gor Apr 29 '23 at 10:29
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34285431) – colebrookson Apr 30 '23 at 23:59
-1

let me make it more clear

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file
  • 2
    Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. –  Jun 24 '20 at 12:04