user3582590
user3582590

Reputation: 187

Execute JS code from string input

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
}

Upvotes: 1

Views: 1596

Answers (2)

Timothy
Timothy

Reputation: 1160

You would want to use "eval" for this.

function execute(jsCodeString) {
    eval(jsCodeString)
}

See this: Execute JavaScript code stored as a string

Upvotes: 1

Christian Benseler
Christian Benseler

Reputation: 8065

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?

Upvotes: 1

Related Questions