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
  • 5,656
  • 17
  • 70
  • 119

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
  • 7,927
  • 1
  • 33
  • 42
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
  • 270,417
  • 55
  • 406
  • 400
0

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

var operation=12+ sign+ 8
console.log(eval(operation))
empiric
  • 7,825
  • 7
  • 37
  • 48
Negi Rox
  • 3,828
  • 1
  • 11
  • 18
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
  • 7,237
  • 4
  • 28
  • 34