0

Lets think we have this variables

 var x=1;
 var y=2;
 var a = "x>y";

is there a way to make something like;

(if(a){RUN JS CODE;})

. Because in that way it dont get the boolean expresion (x>y) it will get the bunch of character(the string) I know i can separate:

the left expression

the boolean operator

the right expresion

But that is an extra work to the client side device (because is javascript)

Is there a way to do like "LITERAL STRING" to "Boolean Expresion"

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3657540
  • 97
  • 1
  • 12
  • Where does this string come from? Is this code running in the browser or on the server? – tadman Aug 24 '17 at 21:46
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval – Isaac Aug 24 '17 at 21:47
  • 1
    Look up for `eval` - and be aware of consequences. – raina77ow Aug 24 '17 at 21:47
  • Is running in the browser, lets think a user can have certain variables and test any boolean expresion he can make, So he put in the input for example "x>y+2" and the program should show true or false. If they put a correct boolean expression with the correct vars. i mean a valid expression – user3657540 Aug 24 '17 at 21:48
  • Thats the answer isaac and raina and r1verside and obsidian. If i can put correct answer every one deserve it. But it don"t let me because i need wait at least 9 mins more to acept a correct answer. In another way... why eval is "evil"? if i can be sure it only run a valid boolean expression it should be fine right ? – user3657540 Aug 24 '17 at 21:53
  • I'd avoid using `eval` and go for [a math parser instead](https://stackoverflow.com/a/1053534/1377002). – Andy Aug 24 '17 at 21:54

2 Answers2

2

What you're looking for is an eval(), which evaluates the string to JavaScript code:

var x = 1;
var y = 2;
var a = "x > y";

if (eval(a)) {
  console.log('triggered');
}
else {
  console.log('not triggered');
}

However, note that eval() can be evil, as it:

  • runs the compiler, which may result in a performance hit
  • runs under escalated privileges, leading to possibly vulnerabilities
  • inherits the execution context and this binding of the scope in which its invoked

As long as you are aware of these issues, and use eval() with caution, you'll be fine to use it.

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
1

You may be able to use if(eval(a)). I didn't tested it but it's what eval does.

To check if the result of the evaluation is a boolean expression you can write

if(typeof eval(a) == 'Boolean') {
    console.log("Boolean expression");
}

Be aware that the use of eval function is highly discouraged.

Douglas Crockford book "JavaScript: The good parts" which I highly recommend to every JavaScript developer, has a chapter on it titled "Eval is Evil" which explains why it is so bad. But just by the title you get an idea.

Pablo Recalde
  • 3,334
  • 1
  • 22
  • 47