JavaScript Mathematical Operators
To perform calculations in our code, we can use operators. You are likely familiar with many common operators from studying maths at school.
Once you feel comfortable with mathematical operators, you’ll never need to do mental arithmetic again! At least, as long as you have a computer nearby…
Arithmetic Operators
There are a many arithmetic operators that can be used to form JavaScript
expressions
.
You may be familiar with operators such as:
- + Addition
- – Subtraction
- * Multiplication
- / Division
These operators can be applied to
data
to create expressions. The data could be literal values, or
variables
that hold these values. We can also store the result of the expressions in variables!
const personOneScore = 40
const personTwoScore = 50
const sumOfScores = personOneScore + personTwoScore
const differenceOfScores = personOneScore – personTwoScore
const doubleScore = personOneScore * 2
const halfScore = personTwoScore / 2
Even though there are multiple pieces of data in expressions like these, when JavaScript performs the operations for us, the end result will always be a single value. Using operators to calculate a result is an example of
evaluation
.
A piece of data used by an operator is called an operand. In the expression 4 * 25, 4 is the first operand, and 25 is the second.
We have two less familiar – but still very useful –
operators
to cover.
Modulo and Exponents
JavaScript has a modulo operator %
that will divide the first
operand
by the second, then
evaluate
to a number showing the remainder. const remainder
=
7
%
3
// 1
The modulo operator is great for finding out whether numbers are even or odd. Even numbers will produce a remainder of 0
when divided by 2
, whereas odd numbers will leave a remainder of 1
when divided by 2
.
The exponentiation operator, **
, multiplies the first operand by itself a number of times equal to the second operand (the exponent). const exponent
=
3const
result
=
2
** exponent
// 8, or 2 * 2 * 2
There are lots of ways of conveying exponent expressions in human language – for example, “two to the power of three” or “two to the third power