2
var x = 10;
var y = 5;
var action = '+';
var z = x action y; //15

is it possible to assign Arithmetic operators as variables?

1
  • Maybe with some preprocessing. In other words, when serving for web you could use server side scripting to transform the javascript code. Commented Feb 16, 2014 at 15:43

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

a switch case might be neater
3

It is not possible using that syntax. The simplest way to do it is to make action a function:

var action = function(a, b) { return a + b; };
...
var z = action(x, y);

Comments

0

Use:

window.eval(x + action + y);

1 Comment

While this is correct, it sould also be pointed out that Eval is Evil, and why it should be used with caution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.