8

I want to store "+" operator in variable.

<head>
<script type="text/javascript">
var m= function(a,b){
return a-b
}
var jj= 10 m 10;
alert(jj)
</script>
</head>
jchand
  • 807
  • 1
  • 10
  • 18

3 Answers3

25

Avoiding the use of eval, I would recommend to use a map of functions :

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

Then you can use

var key = '+';
var c = operators[key](3, 5);

Note that you could also store operators[key] in a variable.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

You cannot store an operator in JavaScript like you have requested. You can store a function to a variable and use that instead.

var plus = function(a, b) { 
    return a + b;
}

Sorry, but JavaScript does not allow this operator overloading.

Ryan
  • 21
  • 3
0

You cannot.

There are ways to use javascript to implement custom versions of operators by playing into the available hooks, but there is no possible way to turn m functionally into +.

@dystroy has an excellent example of using the available hooks to implement a custom version of operators, but note that it is still just a classic example of using an object to access functions which do some work.

Travis J
  • 81,153
  • 41
  • 202
  • 273