The use of eval
is strongly discouraged; in many scenarios it presents a security vulnerability.
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.
Additionally:
You can always run JavaScript from inside itself, although this is strongly discouraged due to the security vulnerabilities it presents (see Remarks for details).
To run JavaScript from inside JavaScript, simply use the below function:
eval("var a = 'Hello, World!'");
You can set a variable to something with the eval()
function by using something similar to the below code:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result, stored in the variable res
, will be:
200
4
27
The use of eval
is strongly discouraged. See the Remarks section for details.
var x = 5;
var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0; ";
console.log("z is ", eval(str));
The use of eval
is strongly discouraged. See the Remarks section for details.
Parameter | Details |
---|---|
string | The JavaScript to be evaluated. |