Is there any way to do the following?
var value = foo;
execute("value = 'bar'");
console.log(value) // returns 'bar'
function execute(jsCodeString) {
// execute js code
}
asked Sep 8, 2014 at 18:12
user3582590
1872 gold badges4 silver badges13 bronze badges
2 Answers 2
You would want to use "eval" for this.
function execute(jsCodeString) {
eval(jsCodeString)
}
answered Sep 8, 2014 at 18:16
Timothy
1,1703 gold badges13 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
user3582590
This answer and Chris's answer were equally good, and I accepted this one at random. +1 for both answers as they are clear and link to documentation.
Use eval()
eval("value = 'bar'");
Anyway, I suggest you to read about the pros and cons of using eval() When is JavaScript's eval() not evil?
answered Sep 8, 2014 at 18:15
Christian Benseler
8,0839 gold badges42 silver badges73 bronze badges
Comments
lang-js
window["value"] = 'bar'would accomplish the same thing.