1

I am setting a state property as such: state = { sign: '' } and set it to either '+' or '-'.

The plan is to then use this within a calculation. For example, imagine sign is set to '+', I will use the operator in a calculation such as: 12 sign 8. However, when I am outputting the result, I am getting 12+8 rather than 20.

Any thoughts on where I am going wrong?

physicsboy
  • 4,797
  • 15
  • 58
  • 96

4 Answers4

2
  1. Using conditionals
  2. Using switch

var sign = '+';
console.log("Using conditionals");
console.log(sign==='+' ? 12+8 : 12-8);

//Switch
console.log("Using switch");
switch(sign)
{
    case '+' : console.log(12+8);break;
    case '-' : console.log(12-8);break;
    default : console.log("not valid operation");
}
Vignesh Raja
  • 6,851
  • 1
  • 28
  • 39
1

Make use of eval function

eval(a + this.state.sign + b)

The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression

Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373
0

there is eval() in javascript to evaluate a string.

var operation=12+ sign+ 8
console.log(eval(operation))
empiric
  • 7,665
  • 6
  • 39
  • 47
Negi Rox
  • 3,666
  • 1
  • 9
  • 17
0

Use eval in javascript

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

 state = { sign: '+' }

console.log(eval(2 + this.state.sign + 6))
Nisal Edu
  • 6,289
  • 4
  • 25
  • 33