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.
In this post, we will discuss how to convert a string into a variable in javascript.
for example, we have a string value ‘helloworld’, we are going to conver this sting to variable as helloworld
let str="helloworld"
function convertToVariable(str){
// helloworld="newHelloworld"
}
Multiple ways we can convert to a variable
[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.
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 an simple example
window["stringvalue"] = "stringdata";
console.log(stringvalue);
🧮 Tags
Recent posts
React Button toggle on off example How to detect production or development build at runtime in React Difference between Development and Production Builds in React ReactJS How to focus input element on render| useRef and useEffect example Reactjs Fix Must call a super constructor in derived class before accessing thisRelated posts