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>
3
  • So you want m to act like a + operator? Commented Feb 1, 2013 at 19:32
  • Javascript doesn't support operator overloading, however @dystroy's answer is interesting, but nothing more than the same as doing an add() function. Commented Feb 1, 2013 at 19:34
  • You didn't put the output that you're expecting from alert(jj), don't leave us guessing... Commented Feb 1, 2013 at 19:36

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're a legend :) thumbs up :+1
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.