I'm trying to code a simple calculator function that takes two numbers and an operator. The example given to me by the guide I'm following is:
if (stringOperator === '+') {
return num1 + num2;
}
else if (stringOperator === '-') {
return num1 - num2;
}
However I wanted to try something different and store the operator (not a string) in a variable and calculate the result that way.
function miniCalculator(num1, num2, stringOperator) {
let operator;
if (stringOperator === '+') {
operator = +
}
else if (stringOperator === '-') {
operator = -
}
else if (stringOperator === '*') {
operator = *
}
else if (stringOperator === '/') {
operator = /
}
return Number(num1) operator Number(num2)
}
For the call miniCalculator(1, 2, "+")
the return value would transform from Number(num1) operator Number(num2)
into the actual calculation 1 + 2
, thus returning 3
.
Why does this not work? And how can I make it work?