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
}
2
  • 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. Commented Sep 8, 2014 at 18:23
  • Why would you want to do that? Where is the string actually coming from (a literal doesn't make sense)? Commented Sep 8, 2014 at 18:29

2 Answers 2

1

You would want to use "eval" for this.

function execute(jsCodeString) {
    eval(jsCodeString)
}

See this: Execute JavaScript code stored as a string

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.