Are Variable Operators Possible? Are Variable Operators Possible? javascript javascript

Are Variable Operators Possible?


Not out of the box. However, it's easy to build by hand in many languages including JS.

var operators = {    '+': function(a, b) { return a + b },    '<': function(a, b) { return a < b },     // ...};var op = '+';alert(operators[op](10, 20));

You can use ascii-based names like plus, to avoid going through strings if you don't need to. However, half of the questions similar to this one were asked because someone had strings representing operators and wanted functions from them.


I believe you want a variable operator. here's one, created as object. you can change the current operation by changing:

[yourObjectName].operation = "<" //changes operation to less thanfunction VarOperator(op) { //you object containing your operator    this.operation = op;    this.evaluate = function evaluate(param1, param2) {        switch(this.operation) {            case "+":                return param1 + param2;            case "-":                return param1 - param2;            case "*":                return param1 * param2;            case "/":                return param1 / param2;            case "<":                return param1 < param2;            case ">":                return param1 > param2;        }    }}//sample usage:var vo = new VarOperator("+"); //initial operation: additionvo.evaluate(21,5); // returns 26vo.operation = "-" // new operation: subtractionvo.evaluate(21,5); //returns 16vo.operation = ">" //new operation: ">"vo.evaluate(21,5); //returns true


We can implement this using eval, since we are using it for operator checking.

var number1 = 30;var number2 = 40;var operator = '===';function evaluate(param1, param2, operator) {  return eval(param1 + operator + param2);}if (evaluate(number1, number2, operator)) {}

in this way we can use dynamic operator evaluation.