How to convert string to the variable name in javascript with example

In this post, we will discuss how to convert a string into a variable in javascript.

for example, if we have a string value ‘helloworld’, we are going to convert this sting to the variable as helloworld

let str = "helloworld";
function convertToVariable(str) {
  // helloworld="newHelloworld"
}

Multiple ways we can convert to a variable

  • using the eval function
  • using window global scope

How to parse string value as a variable name in javascript using eval

eval function is a global function which is sued to execute javascript code in the form of string.

let str = "helloworld";
function convertToVariable(str) {
  var newValue = "newhelloworld";
  eval("var " + str + " = " + "'" + newValue + "'");
  console.log(helloworld); // newhelloworld
}
convertToVariable(str);

In the function, the passed argument is considered as a variable and the new value is assigned to it.

eval function is not suggested as it has performance issues.

convert string to property name using windows global scope

Declared a string object and stored the string and assign the string property variable value with a new value

var str = "helloString";

window[str] = function () {
  console.log("new hello string");
};

helloString();

or here is a simple example

window["stringvalue"] = "stringdata";
console.log(stringvalue);