5

I want to calculate two numbers and its pretty simple.

But Is there any way to take operator in variable and then do the calculation?

var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;

$(".button").click(function() {
  alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
Salman A
  • 262,204
  • 82
  • 430
  • 521
Twix
  • 387
  • 3
  • 15

4 Answers4

15

Avoid eval whenever possible. For this example, a simple switch...case statement will be sufficient:

var x = 5;
var y = 5;
var z;
var p = "+";
switch (p) {
    case "+":
        z = x + y;
        break;
    case "-":
        z = x - y;
        break;
}

You can also use a map of functions:

var fnlist = {
    "+": function(a, b) { return a + b; },
    "-": function(a, b) { return a - b; }
}
var x = 5;
var y = 5;
var p = "+";
var z = fnlist[p](x, y);
Salman A
  • 262,204
  • 82
  • 430
  • 521
7

Or use parseInt on the string which you will be adding the variable to:

 var x = 5;
 var y = 5;
 var p = '-';
 var z = x + parseInt(p + y);

$(".button").click(function(){
  alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
Sidd
  • 1,389
  • 7
  • 17
3

You are looking for eval function:

 var x = 5;
 var y = 5;
 var p = '+';
 var z = x + p + y;

$(".button").click(function(){
  alert(eval(z));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>

However, you have to remember that using eval function is potentially risky. For example, if used in the wrong way it can allow one to make injection attacks. Debugging can be also more difficult. I suggest to read this question.

Community
  • 1
  • 1
Michał Komorowski
  • 6,198
  • 1
  • 20
  • 24
  • Thanks ! Done ..Will accept it after 10 min ..Thank you so much :) – Twix Apr 14 '15 at 08:12
  • 3
    @Twix - remember that using `eval` comes with some warnings - the function will attempt execute **any** JS code that it is provided. Take care to ensure you are only executing code you intend to by validating that your variables contain values/operators that you can "trust". Imagine if one of the variables contained something like `alert('gottcha!')` – Lix Apr 14 '15 at 08:14
0

you can use the eval function:

var x = 5;
var y = 5;
var p = '+';
var z = eval(x + p + y);

alert(z);
TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33
  • If you're gonna suggest using `eval` - please include appropriate warnings about the dangers of executing arbitrary code. – Lix Apr 14 '15 at 08:19