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?