How do I convert a string into an executable line of code in Javascript?

I have the following bit of code

console.log("I am");

var x = "console.log('Alive!')";

Now I only want to use x to execute the code-string that is assigned to it - I may not even know the value of x for example but simply want to execute it whatever it maybe - is this possible?



eval() This will convert string to javascript code.


What you are looking for is eval(). By passing a string to this function you will evaluate the string as JavaScript code and it will return whatever return-value the code in the string returns.

Be aware when using this function though. You do not want to evaluate any code you do not know is safe to execute. For example, running user-generated code could mess up whatever you are making. While using this in JavaScript on a website this will probably only cause issues on the client-side and hence probably won't be much of a security threat, you would want to be VERY careful when evaluating code on for example a server side.

As have been hinted to in other posts here you probably want to make a function instead of an evaluated string if you are in control of the source code that is to be run.


eval and new Function let you parse and execute JavaScript code from strings.

In general, avoid executing code from strings. And never execute code from strings where the strings are untrusted input (for instance, if you take input from user A, never use these to evaluate it in a session with user B).

I see answers here pointing you at eval. eval grants access to your local variables and such to the code, making it really powerful and really dangerous if you use it with untrusted input.

Where possible, avoid eval. You can easily avoid it in your case:

For instance:

console.log("I am");
var x = "console.log('Alive!')";
new Function(x)();

That code creates a function whose body is the text from x, then immediately executes the function.


What you are looking for is called a function:

function x() {

If x is already a string containing the code you could use eval(x) to execute it. eval is evil though.

var x = "console.log('Alive!')";


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.