0

Is it possible to make an operator type of string into operator

<script>
  var operator        = $(this).val();  returns a string eg) + or -
  var quantity        = 5 operator 1;
</script>

currently i am using switch

4
  • You won't be able to do this if you have the following syntax var quantity = 5 operator 1; (which is incorrect), but you will be able if you have a string like var quantity = '5 operator 1';. Commented Dec 2, 2015 at 7:22
  • var result = eval("5 " + operator + " 1"); // 6 if operator is + , this is working yaar Commented Dec 2, 2015 at 7:30
  • I would recommend another approach, as all answers says: eval is not a good way to go. Through my years of programming I have still not encountered a single problem where eval would be the best answer. Commented Dec 2, 2015 at 7:45
  • content is just numbers and +,- operator , its in my control , so i guess i will not face any problems in that , thanks fr your valuable time Commented Dec 2, 2015 at 8:08

3 Answers 3

1

It's possible, in a way, via eval, but see caveats. Example:

var result = eval("5 " + operator + " 1"); // 6 if operator is +

The problem with eval is that it's a full JavaScript evaluator, and so you have to be really sure that the content is under your control. User-contributed content, for instance, is something you have to be very, very cautious with.

Alternately, just do a switch:

switch (operator) {
    case "+":
        result = 5 + 1;
        break;
    case "-":
        result = 5 - 1;
        break;
    case "/":
        result = 5 / 1;
        break;
    case "*":
        result = 5 * 1;
        break;
    // ...and so on, for your supported operators
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your fast responce i am following the var result = eval("5 " + operator + " 1"); approach. it is simple and one lined
yeah content is just numbers and +,- operator , its in my control
1

The absolutely most simple way would be to use a if:

var operator = $(this).val(); // returns a string eg) + or -
var quantity;
if(operator === '-') {
    quantity = 5 - 1;
} else if(operator === '+') {
    quantity = 5 + 1;
}

You could also use the eval function, but eval is very rarely recommended and is not really worth it in a case like this.

Comments

0

No. The easiest would be to use eval:

var quantity = eval("5 " + operator + " 1");

but it is considered a bad practice. Eval is Evil. Not only do you have security concerns, it also slows down the execution of your code.

Rather, this approach is much better and safer:

var operators = {
  "+": function(a, b) { return a + b; };
  "-": function(a, b) { return a - b; };
};

var operatorFunction = operators[operator];
if (operatorFunction) {
  var quantity = operatorFunction(5, 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.