JS Calculator - Feedback and Follow-Up Questions

Hi Campers!

I would like to get some feedback on my JS calculator. I also have some follow up questions.

  1. The use of “eval( )” ?
    To solve the string equation, I decided to use the “eval( )” JS function. I read up about eval( ) on stack overflow, and I understand that it is actively discouraged, because it is vulnerable to “cross-scripting” attacks. However, I also read that this type of operation, namely converting string equations to an answer, is exactly what “eval( )” is built for, as long as the input is controlled, predictable, and sanitized by a regex. (Stack Overflow: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval) What is FCC’s stance on “eval()”? And is there an alternative to using this, other than building my own Parser? What is a “cross-scripting” attack?

  2. Creating the Javascript Button Logic
    The trickiest part to this challenge is building out the JS button logic for computing the numbers and cleaning the equation string to make it work. I created a series of “if-then” statements, but I definitely think that the logic could be written more cleanly. Is there a better way to write the button logic, maybe through switch statements, that make it more elegant?

  3. Calculating the string equation at the “equals” button
    I decided to calculate the equation string only when the user hits the “equals” button. I noticed that the calculator app on my android phone can return the answer “in real time”, as I am typing the equation. :sweat_smile: Any potential explanation on how they did that?

For your Question 1, from what I read, you can use eval for this project.

Would I recommend using eval in professional projects? Probably not, I am pretty sure there’s a library out there that helps parse math equations, or you could make your own but I am pretty sure that would be way out of scope for this project’s demands.

TL;DR: Use eval for FCC project, but avoid using it in professional projects instead
use library or make your own.

1 Like