Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store operator in variable using javascript [duplicate]

Tags:

javascript

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>
like image 923
jchand Avatar asked Feb 01 '13 19:02

jchand


1 Answers

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.

like image 114
Denys Séguret Avatar answered Sep 30 '22 21:09

Denys Séguret