How reliable is eval?

Goodday to everyone who sees this. I am currently working on a react-Calculator and I was wondering if using the function “eval()” is a good way to quickly calculate code. I have heard that “eval()” can be dangerous and should not be used often. is this something I should ignore or should I just make my own function?

eval() is just another function in JS arsenal, there’s no need to demonize it really. It’s very harmful in only one situation: when you run eval on user input on the server - that’s it! Now, calculator indeed uses user input, but it’s a standalone app that runs on the client and there’s absolutely no harm from using one!

Another question, is eval actually good in calculating numbers? And the answer - it kinda sucks: eval('0.2 + 0.1') and so you probably shouldn’t use it - not because it’s dangerous, but because it’s not the best option when it comes to calculating numbers. If you need something better, check this one out: https://mathjs.org/index.html
It’s way more awesome!

4 Likes

eval sometimes useful on certain usage such as parsing script from user. However, you must not allow JS to eval code from URL. That poses XSS attack!

Here’s an interactive demo of XSS attack:
https://www.google.com/about/appsecurity/learning/xss/

2 Likes