Skip to content Skip to sidebar Skip to footer

How To Store Operator In Variable Using Javascript

I want to store '+' operator in variable.

Solution 1:

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.


Solution 2:

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.


Solution 3:

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.


Post a Comment for "How To Store Operator In Variable Using Javascript"