Reputation: 245
So, lets say I have a string defined in javascript:
var s = "function();"
Can I execute the code if I know the value of the string?
And if yes, then can I have multiple commands inside a string? For instance:
var k = "function(); a = a + 1;"
Thanks in advance
Upvotes: 2
Views: 4506
Reputation: 12402
You can use eval
, and yes multiple statements will be executed. BUT, it is generally a bad idea to use eval
. In most cases you can probably accomplish whatever you are trying to do without eval
.
eval
can be quite dangerous if used with user supplied code, such as something from a form or URL. It opens you up to Cross-Site Scripting (XSS) attacks. Just avoiding it is the best course of action, as this answer mentions, sanitizing input before putting it through eval
is not at all straight forward and very error prone.
A couple of other less important problems with using eval
are that it makes code hard to debug and it is slow. It makes it hard if not impossible for browsers to optimize and/or cache it like they do other code.
Update
I'm surprised I neglected to mention this when I originally answered this, but explicitly using the eval
statement is not the only way eval
can be invoked in JavaScript. Passing code instead of a function reference to setTimeout
or setInterval
will implicitly eval that code.
// This evals:
setTimeout("doSomething()", 1000);
// This does not eval:
setTimeout(doSomething, 1000); // also shorter :)
Although not exactly the same as eval
, the Function
constructor also has similar security concerns associated with it.
let xss = 'alert("XSS")';
// whatever is in the string passed to Function
// becomes the body of the function
let doSomething = new Function(xss);
document.querySelector('button').addEventListener('click', doSomething, false);
<button>Do Something</button>
Just as with eval
, care should be taken when using strings as input for setTimeout
, setInterval
or the Function
constructor, especially if user input is going to be passed into them.
Also see:
Upvotes: 1
Reputation: 132
The eval
function will evaluate a string that is passed to it.
it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.
Upvotes: 0
Reputation: 3356
You can use eval()
to Evaluate/Execute JavaScript code/expressions:
var k = "var a = 0; alert(a); a = a + 1; alert(a);"
eval(k);
Upvotes: 0