0

I have a variable

var condition = "if(2 > 5)";

And sometime it will be

var condition = "if(3>5 && 4<2){quantity = 45;} else quantity=60;";

How I can compile these conditions, as these are in string variable?

4
  • you need to seperate them in array and then work accordingly for each conditions Commented Aug 23, 2017 at 16:18
  • 3
    Have you looked into eval()? Commented Aug 23, 2017 at 16:18
  • eval() will make it but think twice before using it Commented Aug 23, 2017 at 16:20
  • i pass the complete condition to eval function which is If (22.13> 72) QTY=3; else QTY=2; but it gives me an error "Unexpected identifier" Commented Aug 23, 2017 at 17:45

1 Answer 1

1

It's dangerous to use because it can allow most anything to be injected into your code, but eval is the right thing to use here, if you really do have to have string evaluated to code.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

eval(condition)

Sign up to request clarification or add additional context in comments.

3 Comments

how i can pass the complete condition like If (22.13> 72) QTY=3; else QTY=2
Thanks a lot, its compiled,
eval("if(2>4){ a=4} else {a=5}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.