var x = 10;
var y = 5;
var action = '+';
var z = x action y; //15
is it possible to assign Arithmetic operators as variables?
var x = 10;
var y = 5;
var action = '+';
var z = x action y; //15
is it possible to assign Arithmetic operators as variables?
You could just check for the actions you wanna be supporting:
var x = 10;
var y = 5;
var action = '+';
var z = null;
if (action == '+') {
z = x + y;
} else if (action == '-') {
z = x - y;
} else if (action == '*') {
z = x * y;
} else if (action == '/') {
z = x / y;
} else {
alert('Unsupported action');
}
There's also the eval function which allows you to execute some dynamic javascript statement but its use is often frowned upon:
var x = 10;
var y = 5;
var action = '+';
var z = window.eval(x + action + y);
Use:
window.eval(x + action + y);