Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Math operation with dynamical sign

I want to do a random math task with a random math operation sign in the middle.

The Random Numbers are fine. I do it with:

function getRandomInt(min, max) 
{
  return Math.floor(Math.random() * (max - min)) + min;
}

and save this return into var number1 and number2

Now the problem.

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

var mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
mathResult = number1 +mathOperation+ number2;
console.log(mathResult) 

Output is: "1+1" (not 2)

The output is a string and not a ResultInt. I know the number1+mathOperation+number2 are do it but I want a mathResult and not a String together.

How can i fix it?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the eval function which evaluates arbitrary JavaScript code as a string.

Warning: eval is VERY dangerous due to XSS vulnerabilities and should never be used to execute non-serialized user input.

const number1 = 3, number2 = 4;

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

const mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
const mathResult = eval(`${number1}${mathOperation}${number2}`);
console.log(mathResult);

Using switch-case (safer)

const number1 = 3, number2 = 4;

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

function performOperation(left, right, operator) {
  switch (operator) {
    case "+":
      return left + right;
    case "-":
      return left - right;
    case "*":
      return left * right;
    case "/":
      return left / right;
  }
}

const mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
const mathResult = performOperation(number1, number2, mathOperation);
console.log(mathResult);

about 4 years ago · Juan Pablo Isaza Report

0

What not to do

You should not use eval() as it can introduces serious security issues and it is just bad practice. In your case there is not much risk as the values at the moment are not supplied by a user, but once they are you can get into serious trouble.

Let's assume you let users provide values for number and you don't check them appropriately then the following would constitute a successful Denial of Service (DoS) attack on your program because this will cause an infinite loop.

const number1 = "for(;;);";
const mathOperation = "+";
const number2 = 2;
eval(number1 + mathOperation + number2);

It also opens up other attack vectors, so just don't use eval().

What to do instead

Instead declare an array of functions, one function for every operation and randomly choose one function.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

const mathOperationList = [
  { func: (a, b) => a + b, symbol: "+" },
  { func: (a, b) => a - b, symbol: "-" },
  { func: (a, b) => a * b, symbol: "*" },
  { func: (a, b) => a / b, symbol: "/" },
];

function getRandomOperation() {
  const randomMathOperation =
    mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

const { func: mathOperation, symbol } = getRandomOperation();
const number1 = getRandomInt(1, 10);
const number2 = getRandomInt(1, 10);
console.log("What is " + number1 + " " + symbol + " " + number2 + "?");
const mathResult = mathOperation(number1, number2);
console.log(mathResult);

about 4 years ago · Juan Pablo Isaza Report

0

You could take an object with all functions and get the operator first.

const
    getRandomOperator = () => operators[Math.floor(Math.random() * operators.length)],
    operators = ['+', '-', '*', '/'],
    functions = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    operator = getRandomOperator(),
    number1 = 10,
    number2 = 5,
    result = functions[operator](number1, number2);

console.log(`What is ${number1} ${operator} ${number2}?`);
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!