0

So, I created a calculator and my equals button uses the eval() function. I'm looking for an alternative to using the eval function because I keep getting security warnings about the danger of using eval. Does this mean that someone can hack my computer through my equals button?

The code can be found on line 51 of calculator base component here:

handleEquals() {
  this.setState(prevState => {
    return {
      output: isNaN(prevState.output.toString().slice(-1))
        ? prevState.output
        : eval(prevState.output)
    }
  })
}
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
  • 2
    Use a maths library that parses and evaluates formulas. – Bergi Dec 10 '19 at 14:02
  • 1
    Eval won't lead to any local security issues. That is to say, no one will be able to hack your computer just because you are using eval. Eval is considered dangerous because [it makes injection attacks trivial to execute](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea). – Fdebijl Dec 10 '19 at 14:03
  • How `prevState.output ` looks like – Dupocas Dec 10 '19 at 14:03
  • With *your code*, there doesn't seem to be an alternative. Except, I suppose, using `new Function`. But if you're storing everything as a string, anyway it's kind of hard to work from it. A much better implementation would utilise a parser. You *could* run the parser at the `handleEquals` stage, parse the string and evaluate it, but it would be even better if you did all the tokenization + representing the (intermediary) steps as the user is entering input. Then at `handleEquals` you have everything needed to just apply the operations and get the result. – VLAZ Dec 10 '19 at 14:05

1 Answers1

1

You would need to parse the expression. Either you do this by your self or use an library like math.js (see this example.

Although I would not recommend you to write your own parser for these expressions, here is an article I found that looks like it would get you started: https://www.freecodecamp.org/news/parsing-math-expressions-with-javascript-7e8f5572276e/

Another workaround would be to tokenize the term automatically, instead of creating a string. By this I mean to store each term typed in into the calculator in an object or something like that. You would still need to parse the tokens, but not the string afterwards.

Janis Jansen
  • 996
  • 1
  • 16
  • 36