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.

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. You don’t need to know too much about querySelector, but if you’d like to here’s a quick definition. Basically, it means get the first element that matches what querySelector has in ().

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, still working in calculate.js.

  • 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 might 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 (we are still working with the calculate.js file). Here’s more info about using .onclick.

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.

Let’s break down this function a little more, shall we?

The word function simply means we are defining a function (not to be confused with calling a function, which is the instance you want to apply a function, in our case, we call our functions with the buttons). The word add is just the name of the function. If we were using parameters it’d go in the () next to add, but we’re not using that for this function, so we leave that part blank. You have to have those (), blank or not, next to your function name. As mentioned previously in this lesson, let is a way to create new variables, so let addition1 is basically saying let’s create a new variable called addition1, which is a number (not a string, AKA text) from whatever the input1.value is. Let sum is saying, let this new variable sum equal addition1 + addition2 (those variables we just defined). outputField.value = sum returns the variable sum in our output field.

If this doesn’t quite make sense yet, don’t worry. The more you work with functions, the more FCC you complete, the more they will make sense. And you’re not done practicing with functions in this lesson yet!

Are you having trouble getting your numbers to add? Click the life preserver!

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 (albeit funky) calculator! For your sanity and mine, use the same output field.

Need a hint on how to get started? Let’s start with the subtraction button. In your JS file, you’ll need to write: let subButton = document.querySelector(‘#subButton’);. subButton then becomes the id of the button in your HTML file. Back in your JS file, you’ll need to define function sub — and you can reuse most of your script from your function add, except for perhaps the let sum line, right? That’s the one with the actual math equation on it…. so maybe you just need to change the plus sign to the minus sign. Try to figure it out on your own! Remember, developers are lazy and we want to reuse as most code as possible.


Before we leave our lovely, powerful, impressive 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. Also, note the “$” is in quotes because it’s a string. Concatenation (con+cat+uh+nation) is a fancy word which means to combine two values together.

If you wanted to make this calculator user-friendly and prettier, how would you do that? Perhaps with CSS, yes? Seeing how HTML, JS, and CSS all work together? We don’t have time for that though, so let’s continue with the JS stuff!