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"

6
  • Where does this string come from? Is this code running in the browser or on the server? Commented Aug 24, 2017 at 21:46
  • developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Aug 24, 2017 at 21:47
  • 1
    Look up for eval - and be aware of consequences. Commented Aug 24, 2017 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 Commented Aug 24, 2017 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 ? Commented Aug 24, 2017 at 21:53

2 Answers 2

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! :)

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

Comments

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.

Comments

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.