Javascript Calculator function: how does it work?

I am going through some tutorials and see this block of code that I cannot understand. Can anyone walk me through this please? I don't understand how the return ends up doing a variable function.

var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
  '+': plus,
  '-': minus
};

var calculate = function(x, y, operation){
    return operations[operation](x, y);
}

calculate(38, 4, '+');
calculate(47, 3, '-');

      

+3


source to share


3 answers


Description

Check out my comments for an explanation.



var plus = function(x,y){ return x + y }; //-- var plus contains this function now.
var minus = function(x,y){ return x - y };
var operations = {
  '+': plus, //-- This states that '+' contains the plus function.
  '-': minus //-- This states that '-' contains the minus function.
};
var calculate = function(x, y, operation){ //-- operation makes it able to select a function from operations.
    return operations[operation](x, y);
}
calculate(38, 4, '+'); //-- The '+' selects the plus function here.
calculate(47, 3, '-'); //-- The '-' selects the minus function here.

      

+2


source


Operations

is an object that has + and - as keys, so by passing one of them you get

operations['+'] = plus

      

Now the parentheses indicate a function call, which can also be made using a variable, as in this case. So the return statement is nothing more than

return plus(x,y);

      




var calculate = function(x, y, operation){

    return operations[operation](x, y); // operations['+'] = plus
}

      

Which calls the method above and returns the value returned by that method.

+3


source


Executions will be something like this:

The first argument is passed as the key of the object, and the corresponding function is executed with the arguments.

var calculate=function(x, y, operation)
        {
            //operations['+'](38, 4);
            //operations['-'](47, 3);
            return operations[operation](x, y);
        };

      

+2


source







All Articles