Why does 50+50 using Function() not equal 100 by comparison?

Viewed 30

I have an input form where the user can input a value such as 300+300 (to return 600) or 300-150 (to return 150). I'm using the function and was testing this on a few values and found that:

const computeValue = (num) => {
  // eslint-disable-next-line no-new-func
  let res = Function("return " + num)()
  return res;
}

let a = '50'
let b = computeValue(50).toString()
console.log(typeof a, typeof b)
let c = a === b /* returns true */
console.log(c)

// BUT: 


a = '50'
b = computeValue('25 + 25')
console.log(typeof a, typeof b)

c = a === b /* returns false! */
console.log(c)

and when I console.log(a, b) it shows a = 50 and b = 50!. I also compared types and they're both strings of the same length.

Does anyone know the reason behind this behavior?

0 Answers
Related