1

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
}
user3582590
  • 187
  • 2
  • 4
  • 13
  • 1
    The other question is, "Are you sure that you have to execute your code this way?". I think `window["value"] = 'bar'` would accomplish the same thing. – Teepeemm Sep 08 '14 at 18:23
  • Why would you want to do that? Where is the string actually coming from (a literal doesn't make sense)? – Bergi Sep 08 '14 at 18:29

2 Answers2

1

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?

Community
  • 1
  • 1
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
1

You would want to use "eval" for this.

function execute(jsCodeString) {
    eval(jsCodeString)
}

See this: Execute JavaScript code stored as a string

Community
  • 1
  • 1
Timothy
  • 1,198
  • 3
  • 10
  • 30
  • 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. – user3582590 Sep 09 '14 at 12:53