Command Shift

Arithmetic operators

This group of operators allow us to do mathematical calculations in our programs. Again, they are best used with numbers - if you use them with other types, you might get unexpected results.

Learning Objectives

  • Understand how to use arithmetic operators to do simple calculations involving numbers
  • Understand that we can also use the addition operator to combine string values.

Add (+), Subtract (-), Multiply (*), Divide (/)

These four operators allows us to use basic arithmetic to combine two numbers into a new number:

greater than operators

No great surprises there.

Additionally, it's very common to use the addition operator + with strings as well as numbers. The result will be the two strings joined together - this is called string concatenation:

string concatenation

Remainder (%)

In mathematics, this operator is called the modulo operator.

It allows you to find the remainder when two numbers are divided - that is the part left over after the division.

For example:

  • If you divide 5 by 4, the remainder is 1, because 5 is (4 x 1) + 1.
  • If you divide 9 by 4, then the remainder is also 1, because 9 is (4 x 2) + 1.

It might seem a little obscure, and definitely a bit confusing at first, but it's actually a very useful operator when dealing with lists, which we will see later.

An example of where remainders are used in everyday life is when converting between 24 hour and 12 hour clocks. To do this, we find the remainder when dividing the time in 24h format by 12.

For example 13:00 in 24h format is the same as 01:00 in 12h format, and 20:00 in 24h format is the same as 08:00:

remainders

Exponentiation (**)

This operator is also known as the power operator. It gives you the result of multiplying a number by itself a certain number of times.

In English, we might say '2 to the power of 3'. This would be the same as saying 2 x 2 x 2, which is 8.

In JavaScript this would look like this:

exponentiation

On this page