Skip to navigation

Doing Math

Variables can be used to store strings and numbers (amongst other things), but here the focus is on numbers.

How much fruit?

In your console, let’s create two variables. One will be the number of apples we have, the second will be the number of pears.

var apples = 5, pears = 10;

That creates two variables… but there’s only one var keyword? Yup, it’s a shorthand for declaring and initializing multiple variables at the same time. By using the var keyword once and separating the new variables with commas you can save yourself some work.

Now, use these two variables to figure out how many pieces of fruit there are in total.

var piecesOfFruit = apples + pears;

So that’s new.

You’re asking the browser to work out the sum on the right before assigning the result to piecesOfFruit - and you’re not adding the variable names, you’re adding the values of the variables. The browser knows that, when it sees a variable like this, you want to do something with the value. So it goes and gets each variable’s value before doing the sum.

The sum is called piecesOfFruit, not pieces of fruit. This is because variable names cannot contain spaces! There’s a set of rules somewhere about what you can and can’t use, but for now just use letters with no spaces.

Splitting the fruit

Let’s say you want to split your fruit between 3 people. How much fruit does each person get?

var piecesForEachPerson = piecesOfFruit / 3;

Thank goodness we have this JavaScript thing, otherwise you’d need a calculator for that one…

You’re using a forward slash (“ / ”) to indicate division: divide the thing on the left by the thing on the right.

Precedence & operators

For doing sums you can use various symbols: add (“ + ”), subtract (“ - ”), divide (“ / ”) and multiply (“ * ”).

Mathematical symbols are called operators; that is, they operate on some data. We’ll meet even more operators later on, but you should know that, like on a calculator, the symbols are worked out in a particular order, called operator precedence. Things in parentheses - that’s these: “ ( ” and “ ) ” - are done first, then multiplication and division, then addition and subtraction.

Here’s an example, stepping through how the browser runs it:

(10 + 2) / 2 + 4 * 2

The part in brackets is worked out first. So this becomes…

12 / 2 + 4 * 2

…which works out to…

6 + 4 * 2

Then things are done in operator precedence order. If multiple sums are of the same precedence then they are evaluated left to right.

The multiplication is higher precedence so is done first, which works out to…

6 + 8

This is used to work out the final value: