Learn Core learning modules JavaScript Numbers and operators English (US)
Basic math in JavaScript — numbers
and operators
Previous Overview: Dynamic scripting with JavaScript Next
At this point in the course, we discuss math in JavaScript — how we can use operators and other features to successfully
manipulate numbers to do our bidding.
Prerequisites: An understanding of HTML and the fundamentals of CSS.
Basic number operations in JavaScript, such as add, subtract, multiply, and divide.
numbers are not numbers if they are defined as strings, and can cause calculations to go
wrong.
Converting strings to numbers with Number() .
Learning
Operator precedence.
outcomes:
Incrementing and decrementing.
Assignment and comparison operators.
Basic Math object methods, such as [Link]() , [Link]() , and
[Link]() .
Everybody loves math
Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and
long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a
fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript
(or any other language for that matter) — so much of what we do relies on processing numerical data, calculating new
values, and so on, that you won't be surprised to learn that JavaScript has a full-featured set of math functions available.
This article discusses only the basic parts that you need to know now.
Types of numbers
In programming, even the humble decimal number system that we all know so well is more complicated than you might
think. We use different terms to describe different types of decimal numbers, for example:
Integers are numbers without a fractional part. They can either be positive or negative, e.g., 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5 and 56.7786543.
We even have different types of number systems! Decimal is base 10 (meaning it uses 0–9 in each digit), but we also have
things like:
Binary — The lowest level language of computers; 0s and 1s.
Octal — Base 8, uses 0–7 in each digit.
Hexadecimal — Base 16, uses 0–9 and then a–f in each digit. You may have encountered these numbers before when
setting colors in CSS.
Before you start to worry about your brain melting, stop right there! For a start, we are just going to stick to decimal
numbers throughout this course; you'll rarely need to start thinking about other types, if ever.
The second bit of good news is that, unlike some other programming languages, JavaScript has only one data type to
represent basic numbers — both integers and decimals. You guessed it, Number . This means that whatever type of numbers
you are dealing with in JavaScript, you handle them in the same way.
Note: JavaScript has a second number type, BigInt, used for very, very large integers. But in this course, we'll only
worry about Number values.
It's all numbers to me
Let's quickly play with some numbers to reacquaint ourselves with the basic syntax we need. Enter the commands listed
below into your developer tools JavaScript console.
1. First of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type
the variable names back in to check that everything is in order:
JS
const myInt = 5;
const myFloat = 6.667;
myInt;
myFloat;
2. Number values are typed in without quote marks — try declaring and initializing a couple more variables containing
numbers before you move on.
3. Now let's check that both our original variables are of the same data type. There is an operator called typeof in
JavaScript that does this. Enter the two lines below as shown:
JS
typeof myInt;
typeof myFloat;
You should get "number" returned in both cases — this makes things a lot easier for us than if different numbers had
different data types and we had to deal with them differently. Phew!
Useful Number methods
The Number object, an instance of which represents all standard numbers you'll use in your JavaScript, provides several
methods to manipulate numbers. We don't cover these in detail here because we wanted to cover only the essentials for
now; however, once you've read through this module a couple of times, it is worth going to the object reference pages to
learn what's available.
For example, to round your number to a fixed number of decimal places, use the toFixed() method. Type the following
lines into your browser's console :
JS
const lotsOfDecimal = 1.7665849587;
lotsOfDecimal;
const twoDecimalPlaces = [Link](2);
twoDecimalPlaces;
Converting to number data types
Sometimes you might end up with a number stored as a string type, which is difficult to use in calculations. This most
commonly happens when data is entered into a form input and the input type is text. There is a way to solve this problem —
passing the string value in to the Number() constructor to return a number version of the same value.
For example, try typing these lines into your console:
JS
let myNumber = "74";
myNumber += 3;
You end up with the result 743, not 77, because myNumber is actually defined as a string. You can test this by typing in the
following:
JS
typeof myNumber;
To fix the calculation, you can do this:
JS
let myNumber = "74";
myNumber = Number(myNumber) + 3;
The result is then 77, as initially expected.
Arithmetic operators
Arithmetic operators are used for performing mathematical calculations in JavaScript:
Operator Name Purpose Example
+ Addition Adds two numbers together. 6 + 9
- Subtraction Subtracts the right number from the left. 20 - 15
* Multiplication Multiplies two numbers together. 3 * 7
/ Division Divides the left number by the right. 10 / 5
Remainder Returns the remainder left over after you've 8 % 3 (returns 2, as three
% (sometimes called divided the left number into multiple integer goes into 8 twice, leaving 2
modulo) portions equal to the right number. left over).
Raises a base number to the exponent power, 5 ** 2 (returns 25 ,
** Exponent that is, the base number multiplied by itself, which is the same as 5 *
exponent times. 5 ).
Note: You'll sometimes see numbers involved in arithmetic referred to as operands.
Note: You may sometimes see exponents expressed using the older [Link]() method, which works in a very
similar way. For example, in [Link](7, 3) , 7 is the base and 3 is the exponent, so the result of the expression
is 343 . [Link](7, 3) is equivalent to 7**3 .
We probably don't need to teach you basic math, but we would like to test your understanding of how it is represented in
JavaScript. Try entering the examples below into your developer tools JavaScript console to familiarize yourself with the
syntax.
1. First, try entering some simple examples of your own, such as
JS
10 + 7;
9 * 8;
60 % 3;
2. You can also try declaring and initializing some numbers inside variables, and try using those in the sums — the
variables will behave exactly like the values they hold for the sum. For example:
JS
const num1 = 10;
const num2 = 50;
9 * num1;
num1 ** 3;
num2 / num1;
3. Last for this section, try entering some more complex expressions, such as:
JS
5 + 10 * 3;
(num2 % 9) * num1;
num2 + num1 / 8 + 2;
Parts of this last set of calculations might not give you the result you expected; the section below covers why.
Operator precedence
Let's look at the last example from above, assuming that num2 holds the value 50 and num1 holds the value 10 (as originally
stated above):
JS
num2 + num1 / 8 + 2;
As a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10
equals 6".
But the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25".
This is because of operator precedence — some operators are applied before others when calculating the result of a
calculation (referred to as an expression, in programming). Operator precedence in JavaScript is the same as in basic math
— in this case, multiply and divide first, then add and subtract, with the calculation evaluated from left to right.
If you want to override operator precedence, you can put parentheses around the parts that should be dealt with first. So to
get a result of 6, we could do this:
JS
(num2 + num1) / (8 + 2);
Try entering the previous line into the console to test this.
If an expression includes the exponentiation operator ( ** ), it is evaluated after expressions in parentheses but before the
other arithmetic operators. For example:
JS
2 + 3 ** 2;
When entering this into the console, the browser does "3 to the power of 2 equals 9", then "2 plus 9 equals 11".
Try entering the following expressions into the console to demonstrate how expressions in parentheses are evaluated before
exponentiation:
JS
4 + 2 ** 3;
(4 + 2) ** 3;
In the first case, the browser does "2 to the power of 3 equals 8", then "8 add 4". In the second case, it does "4 add 2
equals 6", then "6 to the power of 3".
Note: A full list of all JavaScript operators and their precedence can be found in Operator precedence.
Increment and decrement operators
Sometimes you'll want to repeatedly increase or decrease a numeric variable value by one. This can be conveniently done
using the increment ( ++ ) and decrement ( -- ) operators. We used ++ in our "Guess the number" game back in our first
splash into JavaScript article, when we added 1 to our guessCount variable to keep track of how many guesses the user
has left after each turn.
JS
guessCount++;
Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might
seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will
return an error:
JS
3++;
So, you can only increment an existing variable. Try this:
JS
let num1 = 4;
num1++;
Okay, strangeness number 2! When you do this, you'll see a value of 4 returned — this is because the browser returns the
current value, then increments the variable. You can see that it's been incremented if you return the variable value again:
JS
num1;
The same is true of -- : try the following
JS
let num2 = 6;
num2--;
num2;
Note: You can make the browser do it the other way round — increment/decrement the variable then return the
value — by putting the operator at the start of the variable instead of the end. Try the above examples again, but
this time use ++num1 and --num2 .
Assignment operators
Assignment operators are operators that assign a value to a variable. We have already used the most basic one, = , many
times — it assigns the variable on the left the value stated on the right:
JS
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x = y; // x now contains the same value y contains, 4
But there are more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most
common are listed below:
Shortcut
Operator Name Purpose Example
for
Addition Adds the value on the right to the variable value on x += x = x +
+=
assignment the left, then returns the new variable value 4; 4;
Subtraction Subtracts the value on the right from the variable x -= x = x -
-=
assignment value on the left, and returns the new variable value 3; 3;
Multiplication Multiplies the variable value on the left by the value x *= x = x *
*=
assignment on the right, and returns the new variable value 3; 3;
Division Divides the variable value on the left by the value on x /= x = x /
/=
assignment the right, and returns the new variable value 5; 5;
Try typing some of the above examples into your console to get an idea of how they work. In each case, see if you can
guess the result before you type in the second line.
Note that you can quite happily use other variables on the right-hand side of each expression, for example:
JS
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x *= y; // x now contains the value 12
Note: There are lots of other assignment operators available, but these are the basic ones you should learn now.
Sizing a canvas box
In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a
browser API called the Canvas API. There is no need to worry about how this works — just concentrate on the math for now.
The width and height of the box (in pixels) are defined by the variables x and y , which are initially both given a value of 50.
JS
const canvas = [Link]("canvas");
const para = [Link]("p");
const ctx = [Link]("2d");
// Edit the following two lines ONLY
let x = 50;
let y = 50;
[Link](0, 0, [Link], [Link]);
[Link] = "green";
[Link](10, 10, x, y);
[Link] = `The rectangle is ${x}px wide and ${y}px high.`;
The rectangle is 50px wide and 50px high.
Open the above example in the MDN Playground by clicking the "Play" button, then follow the list of instructions below to
make the box grow/shrink to certain sizes, using certain operators and/or values in each case:
Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7
and an arithmetic operator.
Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and
an arithmetic operator.
Change the line that calculates x so the box is 100px wide, but the 100 is calculated using three numbers and the
subtraction and division operators.
Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 2 and x ,
and the multiplication operator.
Don't worry if you mess the code up. You can always press the Reset button and start again.
Comparison operators
Sometimes we want to run true/false tests and then act accordingly depending on the result — to do this, we use
comparison operators.
Operator Name Purpose Example
Tests whether the left and right values are identical to one 5 === 2 +
=== Strict equality
another 4
Tests whether the left and right values are not identical to one 5 !== 2 +
!== Strict-non-equality
another 3
< Less than Tests whether the left value is smaller than the right one. 10 < 6
> Greater than Tests whether the left value is greater than the right one. 10 > 20
Tests whether the left value is smaller than or equal to the
<= Less than or equal to 3 <= 2
right one.
Greater than or equal Tests whether the left value is greater than or equal to the
>= 5 >= 4
to right one.
Note: You may see some people using == and != in their tests for equality and non-equality. These are valid
operators in JavaScript, but they differ from === / !== . The former versions test whether the values are the same
but not their data types. The latter, strict versions test the equality of both the values and their data types. The strict
versions tend to result in fewer errors, so we recommend you use them.
If you try entering some of these values in a console, you'll see that they all return true / false values — those booleans
we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used
every time we want to make a choice. For example, booleans can be used to:
Display the correct text label on a button depending on whether a feature is turned on or off.
Display a game over message if a game is over or a victory message if the game has been won.
Display the correct seasonal greeting depending on what holiday season it is.
Zoom a map in or out depending on what zoom level is selected.
We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick
example:
HTML
<button>Start machine</button>
<p>The machine is stopped.</p>
JS
const btn = [Link]("button");
const txt = [Link]("p");
[Link]("click", updateBtn);
function updateBtn() {
if ([Link] === "Start machine") {
[Link] = "Stop machine";
[Link] = "The machine has started!";
} else {
[Link] = "Start machine";
[Link] = "The machine is stopped.";
}
}
Start machine
The machine is stopped.
You can see the equality operator being used inside the updateBtn() function. In this case, we are not testing if two
mathematical expressions have the same value — we are testing whether a button's text content contains a certain string —
but this still uses the same principle. If the button's text content is "Start machine" when pressed, we change its label to
"Stop machine" and update the label as appropriate. If the button's text content is "Stop machine" when pressed, we swap
the display back again.
Note: Such a control that swaps between two states is generally referred to as a toggle. It toggles between two
states — light on and light off, walk and run, etc.
Summary
In this article, we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll
see numbers all the time throughout your JavaScript learning, so it's a good idea to get this out of the way now. If you are
one of those people who doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.
In the next article, we'll give you some tests to check how well you've understood and retained this information.
See also
Numbers and strings
Expressions and operators
Previous Overview: Dynamic scripting with JavaScript Next
Your blueprint for a better internet.