# JavaScript Mathematics

When building an interactive web page, online game, or even just a dynamic page layout, maths (or “Math” for our USA Friends) plays a really important role. Games need to know your score, or your position on the board, or how many goals you have scored. A dynamic web page layout needs to know how big your screen is to calculate how large each element on the page needs to be. While some web-based apps (as opposed to native apps) can handle calculations at server level **JavaScript Mathematics** can be used to calculate numbers dynamically without putting extra load on your server.

So as boring as it might sound, you will struggle to build may interactive elements without considering maths. Here we will introduce to you the basics of JavaScript mathematics and then we will build a function to generate two random dice rolls!

## Variables in JavaScript

The first new concept to introduce to you is that of **variables**. A variable is a string (a collection of letters and possibly numbers, but **must start with a letter** to hold a value for you. Think back to learning algebra at school and you might see something like this:

1

`x`

holds the result of 3 + 4. `y`

holds the value of 1 + 1. `z`

holds the value of x + y, making the value of `z`

9.

As simple as this example is `x, y, z`

are **variables**. On their own they are meaningless but once you give them a value they mean something and can be used for calculations.

## Strings Are Not Numbers

Before we dive into more code, there is an important thing to stress here: a string is not a number. A string, remember is a collection of words and numbers. Here’s a demo to explain what I mean:

1

By surrounding a number with speechmarks, the number is interpreted as a **string**. This is different to other programming languages. PHP quite happily knows that `"1" + "2" = 3;`

but for JavaScript `"1" + "2" = "12"`

.

The reason this is important is that taking numbers from form elements *usually* are seen as strings. Fields such as

- SELECT drop-down options
- Tick Box Values
- Text Boxes / Text Areas

All rely on **strings**. This means we need to make sure that the strings are converted to **numbers**.

## Converting Strings to Numbers

I will introduce you to two different kinds of numbers here: **integers** and **floats**. An integer is a whole number (whether positive or negative). A float contains decimal points.

*Convert a String into a Whole Number*

To change a string into a whole number we can use JavaScript’s `parseInt`

function, as follows:

1

Note that this is **not a rounding function**. So if you change the second value to `40.6`

the `parseInt()`

function will still return 40.

*Convert String to a Float*

If your string value has decimal places in them and you want to retain those decimal places then you should use `parseFloat()`

instead of `parseInt()`

.

## Converting Form Fields to Numbers

In the examples below we will be combining functions to grab the values from two drop-down boxes and convert them to an integer before performing mathematical functions on them. Let’s built this together, so first let’s make our form fields.

1

So here we:

- Created two SELECT boxes and gave them each a unique ID
- Created an empty
`<p>`

and gave it and ID. We will use this to output the result of our functions. - Created a button for each of the mathematical functions we will look at

But remember, the drop-down boxes send the numbers as strings! So we need to take the value selected and push it through the `parseInt()`

function:

1

As with our examples of `x`

and `y`

earlier, we have set up variables `number1`

and `number2`

. We grab the selected option and convert it to a whole number. A discussion of Arrays will be a future lesson, but you’ll notice that here we have not use the `this.options[this.selectedIndex]`

from the last lesson. This is because we are not *inside* the object, so we have to grab it remotely using `getElementByID()`

.

Only once our selected options are numbers, can we perform mathematical functions on them.

## Addition

We will first output when the two numbers are added together. Set up a function called `Addition()`

. Scroll to ‘`function Addition()`

‘:

1

The first two lines inside the function we will repeat for most functions in this tutorial. We take the two dropdown boxes and put them into variables `number1`

and `number2`

. Although there’s strictly no need to do it, for clarity we have created a new variable called `output`

.

*Amending a Paragraph Text in JavaScript*

Unlike, say a text box, a paragraph doesn’t have a HTML `value`

you can write to. Instead we are forced to dynamically rewrite the HTML inside that paragraph. We can do this with `document.getElementById('ID NAME').innerHTML`

. So for all our mathematical functions, we will be rewriting the `innerHTML`

value of the paragraph, which we have given the ID of `playingWithMaths`

.

*Performing Addition*

Once you have your numbers, addition is the same as ‘normal’ maths – you just use the `+`

operator. Note however that `+`

**is used to both add numbers and to add strings together**. So

`output = number1 + number2;`

document.getElementById('playingWithMaths').innerHTML = 'Result: '+output;

The first line here is a **mathematical** function, but `'Result: '+output`

creates a string which joins the word ‘Result: ‘ to the actual outcome of `number1 + number2`

.

## Subtraction

As with ‘normal’ maths, you can subtract numbers using `-`

(which is a normal hyphen). Be careful you don’t use what is called an ‘Em Dash’. If you use a hyphen in word processors, such as Microsoft Word, it will convert it to a ‘long dash’. This is **not a valid substract**. If you’re using a code editor or a simple notepad you should be fine. So our new `Subtract()`

function looks something like this:

1

## Multiplication

To multiply two numbers, we can’t use `x`

because that’s a string! And we can’t use `×`

because that’s a HTML special character.

To be able to multiply you instead have to use `*`

(the asterisk which may be above the number 8 on your keyboard). So this is our `Multiply()`

function (scroll to `function Multiply()`

):

1

## Division

Division in JavaScript is carried out with the `/`

operator. Now, I want to hit a couple of other issues here, because division gives rise to fractions. Take the simple sum of `10 / 3 = 3.333333`

. That is the result of there being three 3’s and remainder 1, which is ⅓ (or 0.333333 – recurring ad infinitum).

*Rounding Your Results*

The first thing you might want to do is round your numbers. There are a few ways to do this, using JavaScript’s `Math`

object.

`Math.round()`

: this will round your number up or down depending on how much your fraction is. So 0.4 will be rounded down to 0, but 0.5 will be rounded up to 1.`Math.floor()`

: this will round down your fraction, regardless of how much is left. So 0.4 will be rounded down to 0. 0.5 will also be rounded down to 0.`Math.ceil()`

: like ‘ceiling’ it rounds up regardless of how much is after the decimal point. So 0.4 will be rounded up to 1. 0.5 will also be rounded up to 1.

*Rounding With Decimal Places*

The functions above will round to **whole numbers** but you may want to round to a certain number of decimal places. In this case you can use the following function: `yourVariableName.`

function, where **toFixed(x)**;`x`

is the number of decimal places. It effectively, most of the time uses the same principle as `Math.round()`

but with fractions of numbers rather than whole numbers.

So here’s a function which takes your drop-down boxes and converts the division to 2 decimal places. **Note:** `toFixed()`

enforces the two decimal places even if they are not needed. So if your division result is a whole number, you’ll still get `.00`

on the end:

1

## Division: Getting the ‘Remainder’ Value

If you remember back to school when you did division sums, often you would be asked to divide one number by another and then say **what the remainder is**. By that I mean **10 divided by 3 = 3 remainder 1**.

JavaScript enables us to find this remainder with the `%`

operator. Don’t get confused this is not a percentage, in this situation! This means if you do `x = 10 % 3`

, the answer you will get is 1. We can combine this with a normal division, to be able to output the **10 divided by 3 = 3 remainder 1** by rounding down `Maths.floor()`

as follows (Scroll to `function Difference()`

):

1

## Simple Dice Rolling Function

Let’s say you want to create a game to roll two dice. To keep it simple I mean 6-sided dice, rather than the 12-sided dies used in many modern games. We will be using multiplication and addition for this exercise. We will also be rounding using `Math.floor()`

so will combine a few things learned in this module.

### Random Number Generation

Rolling a dice is, when done properly, a random exercise. We need to generate a random number for each dice. JavaScript provides us with an easy way to do this, with `Math.random()`

. However, this function generates a random decimal **between 0 and 1**. Because dice have six sides (of which side ‘zero’ is non-existent!) we need to generate a random number between 1 and 6.

To create a random number within a certain range of numbers, we need to combine `Math.random()`

with `Math.floor()`

to get whole numbers.

`dice1 = Math.floor((Math.random()*highest_number)+lowest_number);`

You can see I have used two variables `higest_number`

and `lowest_number`

. This will allow you to use 12-sided dice if you want to, or any other number of ‘sides’ for that matter.

**Debugging Note:** there are a lot of brackets in here. Any JavaScript function will have ()’s in play. If you find your code doesn’t work, check that you have the same number of open brackets as you have closing brackets!

### BODMAS Applies Here

Back to school! JavaScript mathematics applies functions in the same order as they did in school (the age old BODMAS aide-memoire) . In this order:

**B**rackets**O**f**D**ivide**M**ultiply**A**ddition**S**ubtract

So if you want something done first surround it in `( )`

‘s! JavaScript also works pretty much from the inside out. So in the case of the `dice1`

code above, they are processed in this order:

`Math.random()*highest_number`

- Add
`lowest_number`

- Round down (via
`Math.floor`

) the result of 1 and 2. - Assign the rounded value to
`dice1`

### The Dice Rolling Script

Putting together all we have learned we can now create our dice rolling script and output it to a paragraph tag using `innerHTML`

. Here it is:

1

## TL;DR JavaScript Mathematics

Maths governs a lot in programming – especially when creating interactive features such as games or dynamic layouts. In this lesson you have learned to perform simple mathematical functions, round numbers and generate random numbers between predefined start and end points.

The companion demo script can be downloaded from here. Take it and play with it to help you solidify what you have learned here!