switz switz - 4 months ago 12
Javascript Question

Convert string to variable name in Javascript

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 and I haven't utilized it once since. Look up how javascript objects work.

a simple intro:

// create javascript object
var obj = { "key1": 0 };

// assign - set "key2" to 1
obj["key2"] = 1;

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

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

// read with a variable
var key1Str = "key1";
obj[key1Str] === 0;


This is much better than using global variables and assigning them via
window[variable]
. Try to only create global variables if you can confidently say you know what you're doing.

Answer

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