Marcio
Marcio

Reputation: 622

dynamical operator javascript

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");       
     }

Upvotes: 1

Views: 62

Answers (2)

Bob Lauer
Bob Lauer

Reputation: 845

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");       
 }

Upvotes: 3

kirilloid
kirilloid

Reputation: 14304

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

Upvotes: 1

Related Questions