Skip to the content

Lesson 31 of 296

Numbers and maths operators

What you will learn

  • The maths operators
  • The order JavaScript does maths in
  • Shortcuts for changing a number
  • Turning text into numbers
  • Rounding and the Math object
  • Decimal errors and how to avoid them
On this page

Maths operators

OperatorNameExampleResult
+Add10 + 313
-Subtract10 - 37
*Multiply10 * 330
/Divide10 / 42.5
%Remainder10 % 31
**Power2 ** 38

The remainder operator %

% gives what is left over after dividing. 10 % 3: 3 goes into 10 three times (9), and 1 is left over.

Common uses:

UseCode
Is a number even?n % 2 === 0
Is a number odd?n % 2 !== 0
Divisible by 3?n % 3 === 0
Last digit of a number1234 % 10 gives 4
Seconds left after full minutes125 % 60 gives 5
Loop back to the start of a list of 5(position + 1) % 5

Trap: the result keeps the sign of the left number. -5 % 2 is -1, not 1. So check odd numbers with !== 0, not === 1.

Order of operations

JavaScript does maths in the same order as school maths (often remembered as BODMAS or BIDMAS):

  1. Brackets ( )
  2. Powers **
  3. Multiply, divide and remainder * / %, from left to right
  4. Add and subtract + -, from left to right
2 + 3 * 4        14   (multiply first)
(2 + 3) * 4      20   (brackets first)
10 - 4 - 3       3    (left to right)

When in doubt, add brackets. They make your intention clear to readers too.

Shortcuts

ShortcutSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2
x++x = x + 1
x--x = x - 1

These only work with let, because they change the variable.

Division by zero

10 / 0       Infinity
-10 / 0      -Infinity
0 / 0        NaN

JavaScript does not crash; it gives these special values. Your code should check for them.

Turning text into numbers

Data from forms and URLs always arrives as strings. You must convert it before doing maths.

Method"42""42.5""42px""abc"""
Number(x)4242.5NaNNaN0
parseInt(x, 10)424242NaNNaN
parseFloat(x)4242.542NaNNaN
  • Number() is strict: the whole string must be a number.
  • parseInt() and parseFloat() read numbers from the start and stop at the first character that is not part of a number.
  • Always pass 10 as the second argument to parseInt, to say "base 10" (normal numbers).
  • Note: Number("") gives 0, which can hide a bug with empty form fields.

Checking for NaN

Number.isNaN(x)

Do not write x === NaN. It is always false, because NaN is the only value in JavaScript that is not equal to itself.

Rounding and the Math object

Math is a built-in object with maths tools.

CodeResultMeaning
Math.round(4.5)5Nearest whole number
Math.floor(4.9)4Round down
Math.ceil(4.1)5Round up
Math.trunc(-4.9)-4Remove the decimal part
Math.abs(-7)7Remove the minus sign
Math.max(3, 9, 2)9The biggest
Math.min(3, 9, 2)2The smallest
Math.sqrt(16)4Square root
Math.random()e.g. 0.6213A random number from 0 up to (not including) 1

A random whole number from 1 to 6 (a dice):

const roll = Math.floor(Math.random() * 6) + 1;

Rounding to 2 decimal places for display:

const price = 12.3456;
price.toFixed(2);        "12.35"  (a string, not a number)

toFixed returns a string. It is for showing numbers, not for more maths.

Decimal errors

0.1 + 0.2        0.30000000000000004

Computers store numbers in binary (0s and 1s). Some decimals, such as 0.1, cannot be stored exactly in binary, so tiny errors appear. This happens in most programming languages, not only JavaScript.

For money, store whole pence (or cents), not pounds with decimals:

const priceInPence = 1099;      £10.99
const total = priceInPence * 3; 3297 pence, exact

Convert to pounds only when you show it to the user.

Common mistakes

  • Doing maths on form values without converting them first.
  • parseInt without the 10.
  • Comparing with NaN using ===.
  • Storing money as decimals.
  • Using toFixed and then doing more maths with the string result.

How to say it in an interview

"JavaScript has one number type for integers and decimals, based on 64-bit floating point, so values like 0.1 plus 0.2 are not exact. For money I store integer pence. I convert strings from inputs with Number, or parseInt with a radix of 10, and check for NaN with Number.isNaN, since NaN is not equal to itself. The remainder operator keeps the sign of the left operand, so I test odd numbers with not equal to zero."

Key words

WordMeaning
OperatorA symbol that does an operation, like +
RemainderWhat is left after dividing, from %
Order of operationsThe order maths is done in
Increment / decrementAdd 1 (++) / subtract 1 (--)
ParseRead text and turn it into another type
NaN"Not a Number": the result of invalid maths
Floating pointThe way computers store decimal numbers, with small errors

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.