1

Using the following 3 variables - I wanted to calculate two numbers with whatever the operator variable was set to. For example -> num1 * num2..

const num1 = 10;
const num2 = 4;
const operator = `*`; //Could be any arithmetic operator

I know this can be done using an if or switch statement, but I'm curious to know if there is a way to do it in less lines of code using the operation variable itself in the actual calculation.

I tried out the following things (I mostly expected them to turn out the way they did):

console.log(num1 + operation + num2);    //Outputs: "10*4"

console.log(num1, operation, num2);    //Outputs: 10 "*" 4

console.log(`${num1} ${operation} ${num2}`);    //Outputs: "10 * 4"

console.log(num1 operation num2);    //Outputs: Error

const calculation = num1 operation num2; console.log(calculation);    //Outputs: Error

console.log(1 + operation + 2);    //Outputs: "1*2"

console.log(Number(1 + operation + 2));    //Outputs: NaN

So is there something I haven't tried yet that would make this work, or can it just not be done like this?

georg
  • 211,518
  • 52
  • 313
  • 390
DaisyMayDev
  • 11
  • 1
  • 3
  • There's no direct way to do that in JavaScript. In Lisp-like languages, the "operators" are functions, so you can achieve what you're attempting. You could of course make your own set of functions as properties of an object. – Pointy May 22 '21 at 14:53

1 Answers1

2

You could take an object with the wanted operators, test if the operator exist, and use it.

var operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    calculate = function (val1, val2, sign) {
        if (sign in operators) {
            return operators[sign](val1, val2);
        }
    }

console.log(calculate(6, 7, '*'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392