Build a calculator!

Free Code Camp is an excellent resource for learning basic Javascript concepts and techniques, but that learning becomes much more valuable when you put it to work inside of an actual html document. In this exercise we are going to build a crude calculator which draw upon those first few Javascript lesson in freecodecamp.org.

Before we go any further we need to fix a small problem with Brackets. For some reason, Brackets has a built in error finder that often cries wolf even when no long-toothed canines are anywhere in the vicinity. This can be pretty annoying so I simply disable this feature. To do the same,Go to Brackets > File > Extension Manager > Default > . Find EsLint and click disable. Then find JsLint and disable that as well. Errors be gone!

With that bit of housekeeping out of the way, let's get started by building ourselves a calculator. Obviously, we all have calculators at our disposal but this exercise isn't really about  math. The process of building your own calculator will actually teach you a lot about numeric and string variables in addition to a tiny bit about math.

Connect js to html and split the screen

  1. Create a new html document named calculate.html, a new javascript document named calculate.js and save both documents into a new folder named basicJavascript.
  2. Create a new folder inside of basicJavascript named js and move calculate.js into it.
  3. Connect calculate.js to calculate.html by typing  (type, don't paste) <script src="  after the </html> tag, browse to calculate.js (inside of the js folder), and connect it. Make sure that you close your script tag.

  4. At this point I recommend that you use Bracket's split screen option, and open calculate.html on one side and calculate.js on the other side.

Build the html document

  1. Let's start by adding a button between your the html page's body tags.   Give your button an id  of "addButton" and some text  between the tags that say add or something to that effect. Your button should look VERY similar to the one shown below.

  2. Next, add three input fields, using the screen capture below as a guide.

    At this point you have two number fields, one text field, and one button. Before we move on, a bit of formatting and labelling would be in order. You can make your own decisions on how to best present everything. The first two fields, input1 and input2 are for inputting numbers to be added. The third field, output, will ultimately show the sum of those numbers.  The purpose of the addButton should be obvious.

Javascript task one: identify the fields and buttons

In order to get information from your text fields and act on that information with the button, Javascript needs to know 'who they are' so to speak. We will accomplish this introduction via the querySelector method.

Open calculate.js and on the first line enter the variable declarations shown below. The main thing for you to understand about this process is that you are creating new variables with the 'let' command, and are using document.querySelector to tie those new variables to the id(s) of your button and textfield elements.
The first line,
let input1 = document.querySelector('#input1'); , creates a variable named input1 that is equal to the textfield with the ID #input1, and the other three lines follow the same pattern.

Javascript task two: Create a function

Our next task is to come up with a way to get the values that are entered into input text fields, add them together, and then enter the sum into the output field. We will accomplish these tasks within a function and then call the function with the button.

The screen capture below shows one way to go about this task.

  • On line one of the add function, a variable named addition1 is tied to the value of the input1 variable that was tied to the the #additionInput1 id in the previous step.
  • Line two works just like line one for the other input value.
  • Line three adds the two numbers from the text field
  • Line four places the sum value into the output text field.

Javascript task three: Call the function

Now that you have a function the next step is call it with the button. You may already know how to call a function directly from a button, as in
<button onclick="add()>, but this method is frowned upon in the serious Javascript community. The preferred method is shown below.

Now test everything. Did it work? Did notice anything a little weird? For example, did the numbers concatenate instead of adding, as in 3 + 4 returns 34 instead of 7? The reason for that problem is that the values from your input fields are not numbers but 'strings' or, in other words, text.

Javascript task 4: Convert strings to numbers

To convert those strings into text, follow the approach shown below in which Javascript's Number method is used to convert the value of input1 and input2 into numbers.

Oddly enough, even though the original input field was set to "number," Both your browser and Javascript still interpret its value as text (or string), and it must be converted to a number before it can be used for anything math related.

More Functions (and more buttons)!

Now that you know how, create three additional functions that divide, multiply and subtract the same values from the same fields. Then add and three additional buttons and use those buttons to call the three new functions. Once you finish, you should have a functional (but funky) calculator!

Concatenation

Before we leave our lovely calculator behind, let's do one more thing. Imagine that it is a financial calculator, and we would like all of the values to appear with a $ (dollar sign) in front of them. Easy!  Just change the lines that say
outputField.value = sum;     to     outputField.value = "$"+sum; 

When you test your calculator again the dollar sign should be appended.

Print Friendly, PDF & Email