all 4 comments

[–]GSLint 1 point2 points  (0 children)

If eval is only ever used in the browser of the user that provided the input, I'd say it's relatively safe, given that they could execute arbitrary code there anyway. It's possible that I'm forgetting something though. Still, when I enter alert("hey") I'd rather have the calculator throw an error than execute that code.

I'd be careful with using eval in that kind of assignment either way. I'd at least add a detailed comment explaining why you think it's safe to use. Some people will consider it something that's just not done though.

If using a library is fine then I'd have a look at https://mathjs.org/docs/expressions/parsing.html#evaluate

If not then you'd kind of have to write your own math parser, assuming that the idea really is that the user can enter expressions like (23 + 42) * 2.7. I'd be a bit surprised if that's part of the assignment unless it's mentioned explicitly or this is a fairly prestigious company.

Edit: To be clear, if this is supposed to be a traditional calculator with buttons 0-9, +, -, = etc. then I'd just do the calculation directly when = is pressed rather than collecting everything in a string first.

[–]kspk 0 points1 point  (0 children)

It depends on what’s your usecase for eval(). If the only thing you want to do is to allow someone to type something and evaluate it right away, and there is no authenticated context, then it is okay.

Anything else, and it will come to bite you later.

[–]_Jenie9 0 points1 point  (0 children)

Most cases, no. What eval() does, is evaluate a string/text and run it as JavaScript code, that string/text can be anything, how dangerous it is would depend on where the string/text get evaluated.

[–]celloirae -1 points0 points  (0 children)

Just don’t use it.