As I journey back into working with Vanilla JS, I came across a nice project to work on that would be a combination of some the skills I’ve been practicing. The focus for this was to build a simple calculator that would be able to execute in the browser and work with some of the HTML events I had been learning previously. I’ll provide some examples below and give a little info on the context of why I made some the decisions in my code.
The first thing we need to do is figure out what we’re working with in our html doc.
We’re using a select input with 4 different options for the operators we’ll be using to evaluate our expression. More info on select can be found here. The key takeaways to keep in mind here are the id’s of each of the elements on the page. Those id’s are going to allow us to do some type of arithmetic based on the users input. If you have some familiarity with manipulating the DOM in vanilla JS, then you know we’ll need to assign our querySelectors to a variable in order to manipulate our browser. This is going to be the first step within our JavaScript code.
At this point we can use a console log to double check we’re actually grabbing the correct components.
We know we have all the necessary elements in order to start formulating an answer, but one key thing to remember is right now JavaScript is interpreting these integers as strings. This becomes a problem, because if we were to do any addition JavaScript would read ‘1’ + ‘1’ = ‘11’. We know this is incorrect, but we’re on the right track. We need to turn our strings of numbers into integers. One way we could do this, is by using the parseInt() function and assigning that to a variable. All parseInt() is doing is taking the value of the number within the string and turning that string into a regular integer. If we log (num1 + num2) we’ll get 11.
Now we have integers and can solve, based on user input using some conditional logic.
In order for all this code to function we need to work with our event handler, basically once a user clicks or submits this info the program needs to know to ‘run it’. We do this using an onclick event and a regular button in the html file.
The onclick will trigger our function Calculator() and run the code we’ve been building. That’s it! The next step for me on this would be to build out more of the classic calculator ‘look’ with some css and styling options, but the logic would still remain the same.