Chingu FCC Speedrun Challenge: JavaScript Calculator

The JavaScript Calculator is my 6th project for the speedrun. At first glance I thought, “It’s just a calculator, I should be able to finish it pretty quickly.” However, the project was surprisingly not simple to build. That said, honestly so far it’s the one I’ve had the most fun working on.

The biggest challenge with this one was figuring out how to do multiple calculations, and also doing multiplicative calculations before handling additive ones. The way I handled this was define an array for all calculations, and once the user clicks the equal button (or hits Enter), the array is iterated once for handling all multiplicative calculations, reducing the array to additive calculations, and then the array is iterated once more for handling those in turn.

For example, let’s assume the user types in 1+2*2/4, then the array would look like this: ["1", "+", "2", "*", "2", "/", "4"]. On first iteration, the array is reduced to the following: ["1", "+", "1"]. On second iteration, 1+1 is evaluated and the result 2 is returned.

Other challenges were preventing multiple consequent operations to be added to the array (e.g. ["1", "+", "*", "2"]), as well as preventing multiple decimal points in decimal numbers. Additionally, handling decimals was also a challenge, and this is the reason numbers are stored in the array as strings as opposed to regular numbers. The reason for this is that JavaScript doesn’t allow trailing zeros after the decimal point, but what if the user wants to type 1.005 for example? Then they wouldn’t be able to do so because the zeros would be ignored, so I figured the best solution would be to just store them as string values and then convert them to numbers when it’s time to do the calculation.

I know the project could probably be done in a better way and more efficiently, but I tried my best to do it the best way possible with my current skillset. Also, as a side note, considering this is a speedrun, I haven’t spent much time making it look closer to a real calculator, but I definitely plan to do so when I build the project as not part of a speedrun.


Previous projects: