# Calculate function with optional operator argument

I am currently learning javascript at university. We have an assignment where we shall write various functions for calculating values. In one case, we shall write a function which returns the sum of two values, if only those two values were passed as arguments. If there is the third optional argument, which shall be an operation like subtract or multiply, than it should return the result of this operation.

Now, my question is: Is this code written in good way or is it like really bad style?

Btw: One assignment before, we should write the add, subtract and multiply functions in inside of this calculate function. So this was set.

 let rechne2b = function(a, b, ...operator){

return a + b;
}

let subtrahiere = function(a, b){
return a - b;
}

let multipliziere = function(a, b){
return a * b;
}

let argsLength = arguments.length

if(argsLength > 2){
switch(arguments.operation){

case "subtrahiere":
return subtrahiere(a, b);
break;

case "multipliziere":
return multipliziere(a, b);
break;
}
} else {
return a + b;
}

}

console.log(rechne2b(4, 5, {operation: "multipliziere"}))


• Use a function declaration function rechne2b(a, b, {operator}){ rather than a function expression let rechne2b = function(a, b, {operator}){
• There is only a single optional argument so don't use the rest operator ...
• The optional argument is passed in an object so you should use destructuring assignment function rechne2b(a, b, {operator}) to extract the operator if given.
• Avoid switch statements if you can by using a lookup (see example)

## Rewrite

function rechne2b(a, b, {operator}) {
const ops = {
subtrahiere(a, b) { return a - b },
multipliziere(a, b) { return a * b },
};
return ops[operator] ? ops[operator](a, b) : a + b;
}