user3657540
user3657540

Reputation: 97

Javascript If BOOL expression from String

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"

Upvotes: 0

Views: 91

Answers (2)

Pablo Recalde
Pablo Recalde

Reputation: 3571

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.

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

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

Upvotes: 2

Related Questions