Codiqo

Learn JavaScript · lesson 2 of 60 · about 6 minutes

Numbers and Arithmetic

Let JavaScript do the maths for your page: add, subtract, multiply, divide and group.

What you'll learn

  • Calculate with + - * and /
  • Know which part of a sum is worked out first
  • Show a result on the page

Let JavaScript do the maths

Your page should say how many days old someone is. You could work it out by hand, but it changes every year, and a slip is easy. JavaScript can do the maths for you.

Numbers don't need quotes. +, -, * and / add, subtract, multiply and divide.

The page shows the answer, not the sum

document.querySelector("#days").textContent = 12 * 365;

The four everyday operators

console.log(7 + 3);
console.log(10 - 4);
console.log(6 * 7);
console.log(10 / 4);

Output

10
6
42
2.5

What's worked out first

Like in maths, * and / happen before + and -. Brackets go first of all, so use them to say what you mean.

Division always keeps the decimals: 7 / 2 is 3.5.

Brackets change the answer

console.log(2 + 3 * 4);
console.log((2 + 3) * 4);

Output

14
20

Tip

Some languages throw away the decimals when you divide whole numbers. JavaScript doesn't: 9 / 2 is 4.5.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.