{

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] (/javascript-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);
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.