There are multiple ways to achieve this.
Function
Create a Function and set the body:
var dynamicJS = "var x = 1+1 return 2;"
var DoSomething = new Function("value", dynamicJS );
eval()
While arguably less secure1, eval() can be used.
var dynamicJS = "function DoSomething(value){var x = 1+1 return 2;}"\
eval(dynamicJS);
Caution
Please read this section of the MDN documentation about eval()
.
Don't use eval needlessly!
eval()
is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval()
with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval()
was invoked, which can lead to possible attacks in ways to which the similar Function
is not susceptible.
eval()
is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
There are safer (and faster!) alternatives to eval()
for common use-cases.
1
See a demonstration of these methods utilized below.
var dynamicJS = "function DoSomething(value){var x = 1+1; return 2;}"
var functionBody = "var x = 1+1; return 2;";
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('eval').addEventListener('click', function() {
eval(dynamicJS);
console.log('DoSomething: ',DoSomething(3));
});
document.getElementById('function').addEventListener('click', function() {
var dynamicFunction = new Function("value", functionBody);
console.log('dynamic function():',dynamicFunction(3));
});
});
<button id="eval">click to eval</button>
<button id="function">click to use Function</button>
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly!