Finishing up Calculator App: eval(), new Function, or other alternative for evaluation?

Hello everyone. I am finishing up my Calculator app, and I’m wondering how should I approach problem of evaluating equations. Everything other is in place: writing digits, operators, brackets and decimals work fine.

How should I approach evaluation of equation? My app writes equations as a string. I’ve looked up eval() function, but learned that it’s very unsafe and should not be used.

BUT, there is other simple alternative - using new Function.

let operation = "2 * 5 + 10"

let evaluation = Function("return " + operation)()

console.log(evaluation) // logs correct result: 20

What do you think about Function method? Is it safer than eval(), or should I write my own way from scratch?

eval is fine as long as you control the input. Which you do in this case.

It is unsafe if it accepts input from untrusted sources.

1 Like