Rahul Sharma Rahul Sharma - 1 month ago 4x
Javascript Question

Convert variable string value to expression in JavaScript

i am trying to convert a string value to expression so that i can use it in if condition like:

var StringVal = '20 > 18 && "yes" == "yes"';



is it possible to do this, please suggest me.



It's not generally safe to take input from a user source and evaluate it, but you could use Function evaluation, or eval

var StringVal = '20 > 18 && "yes" == "yes"';
if (new Function('return (' + StringVal + ')')()) {

Are eval() and new Function() the same thing?

Update: If you could give further information in your question as to why you feel this is necessary along with an example of your actual code, then a safer solution could be suggested.