1

Is there a way to choose dynamicaly an operator

do something like this:

     var ​val1="1",
         val2="1",
         oper="===";
     if(val1 oper val2){
         console.log("im in"); 
     }else{
         console.log("im out");       
     }

2
  • No. (everything else I type is to fulfill the min. character limit). Let's NOT talk about eval(). Commented Mar 20, 2012 at 15:23
  • 1
    If you create an operator -> function map, then yes. eval is an option if you have control over the input. Commented Mar 20, 2012 at 15:25

2 Answers 2

3

You can not do a dynamic operator, but you can achieve the same thing using functions instead.

var ​val1 = "1",
    val2 = "1",
    oper = function(a, b) { return a === b; };

 if(oper(val1, val2)) {
     console.log("im in"); 
 } else {
     console.log("im out");       
 }
Sign up to request clarification or add additional context in comments.

1 Comment

nice approach your doing that's definitly one possibility
1

No javascript syntax allows that. You can generate string with js code and use eval, but you'd better not use eval at all.

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.