Evil Eval( )…?

Emily Deans
2 min readAug 6, 2017

--

A few weeks back, our weekly assignment was to create a basic calculator that was functional and mimicked — as best we could manage — a mockup provided by our instructors (image below may look familiar):

While I felt like my submission was a pretty close aesthetic approximation and was indeed a fully-functional calculator, there was one catch — I had used the ‘eval’ function to calculate the total value of the input operations. The ‘eval( )’ function in JavaScript — for those who haven’t come across it — essentially takes code presented in a string and — you guessed it — evaluates it. Given the task at hand, it seemed obvious enough to me to move forward with this approach to complete my calculator.

Upon submission, however, one of my instructors brought to my attention that using ‘eval’ is not only a ‘bad’ practice, but is also potentially a dangerous one — saw more than one developer refer to it as ‘evil eval’ or ‘B.A.D.’ (Broken As Designed) during my follow-up research.

The big takeaways on the topic seem to be that using ‘eval’ is problematic for the following reasons:
— It can open you up to dangerous attacks if malicious code is injected into your program
— It can slow down the performance of your program because JavaScript will have to compile the function to run while it’s loading the page
— ‘Eval( )’ can also make programs more challenging to debug because you may not be able to see exactly where errors have occurred.

A lot has been written on the subject, so if you’re interested in learning more, I’d recommend taking a look at Eval is Evil, Parts One and Two , by Eric Lippert.

Anyways, with some helpful direction from a classmate, I was able to rework my evaluating function to calculate correctly withOUT using ‘eval’. While it’s definitely a bit more verbose, it does work, and it also doesn’t open the program up to any malicious advances (should this be an actual live application).

Initial Code Using ‘eval( )’
Revised Code

Hope everyone had a great weekend. Excited to work a bit with SQL tomorrow and I’ll see you back here then!

Song of the Day:Cherry Lane” by Ryan Adams

--

--

Emily Deans

Washington, D.C.-based web developer. Former cheesemaker/food-systems nerd and current nerd in general.