0

I wanna basically execute a statement stored in a var. For example, I have this,

var statement = "alert('Hi!')";

How can I make JS execute the statement stored inside the var statement? Thanks a lot guys.

4

5 Answers 5

1

This will do it, but it's not recommended

var statement = "alert('Hi!')";
eval(statement)
Sign up to request clarification or add additional context in comments.

1 Comment

It does not even work. Any other solution?
1

You could use Function constructor

var func = new Function("alert('Hi!')")
func(); // call it

You could eval but this method is comparatively safer.

Comments

1

You're probably looking for eval
var test = "alert('toto')";
eval(test);

Comments

1

you can use eval("my script").

Comments

1

You should be able to use eval() like this:

var statement = 'alert('Hi!');";
eval(statement);

eval is a dangerous thing though and should be used with caution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.