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.

ChemiCalChems
  • 612
  • 12
  • 31

5 Answers5

1

This will do it, but it's not recommended

var statement = "alert('Hi!')";
eval(statement)
roryok
  • 9,325
  • 17
  • 71
  • 138
1

You could use Function constructor

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

You could eval but this method is comparatively safer.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

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

Flo
  • 21
  • 1
  • 5
1

you can use eval("my script").

Sreelal P Mohan
  • 309
  • 1
  • 11
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.

zack.lore
  • 527
  • 5
  • 10