The numbers are in a input text field so when i retrieve it it is in a string. Which I can get the answer but would it be better to use parseInt.
Asked
Active
Viewed 1,835 times
0
-
`eval()` is almost always never the better choice. – j08691 Mar 01 '14 at 23:41
-
I would maybe consider using a library like http://mathjs.org/ I would always try to avoid using eval unless as a last resort. For reasons, please see this thread: http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Mark Mar 01 '14 at 23:41
-
1Never use `eval()`, especially when you can use something like `parseInt()` to solve the same problem. stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Karl-Johan Sjögren Mar 01 '14 at 23:41
-
1If all you want to do is converting a string containing digits to a number, then there is no reason to use `eval`. Even `parseInt` could be overkill. Just use the unary plus operator: `var num = +str;`. – Felix Kling Mar 02 '14 at 01:11
1 Answers
2
In general, avoid using eval
, especially with user input. Arbitrary code execution is almost never what you wanted to do in the first place. As long as the use can't enter a decimal number, parseInt
is the way to go.

mgw854
- 657
- 6
- 17
-
-
I'd disagree. All user input is dirty, and therefore potentially dangerous. Always verify user inputs. – mgw854 Mar 02 '14 at 01:21
-
But you know that the user could just execute their code in the console, if they really wanted to, right? `eval` is dangerous when you pass an *other* user's input. – Felix Kling Mar 02 '14 at 01:22
-
Of course... which is why you can't trust JavaScript or client-side code in general. But arguing that you shouldn't try to stop the user from shooting themselves in the foot because the console exists is a real slippery slope. – mgw854 Mar 02 '14 at 05:08