Arithmetic & assignment
Use JavaScript's arithmetic operators, assignment shortcuts, increments, precedence rules, and string-plus behavior without surprises.
- 01Do math with operatorsUse
+ - * / % **, and plus or minus in front of one value, and know what each gives. - 02Update variablesRead
++,--, and shortcuts like+=as changes to a variable. - 03Know what runs firstUse the order of operators, round brackets, and the string rule for
+to predict answers.
Operators work out values; assignment stores them
Earlier lessons showed you variables, numbers, strings, and type conversion. This lesson puts them to work. You will do math with values and save the answers in variables.
An operator is a symbol that does one job with values. In 2 + 3, the operator is +. The values it works on, 2 and 3, are called its operands. A piece of code that gives a value, like 2 + 3, is called an expression.
Assignment means storing a value in a variable. In total += 5, JavaScript reads total, adds 5, and stores the new number back in total.
Arithmetic operators work out a value. Assignment operators store a value in a variable. When code surprises you, ask two questions: What value does this expression give? and Where is that value stored?
Each calculator button does one job with the numbers you type. You press = to see the answer. Then you can write the answer in a notebook to use later.
- In real life: Pressing × on a calculator
- In JavaScript: Writing
*between two numbers - In real life: Pressing = to see the answer
- In JavaScript: An expression giving a value
- In real life: Writing the answer in a notebook
- In JavaScript: Assignment storing the value in a variable
The lesson goes in this order:
- The six arithmetic operators, like
+and*. - The remainder operator,
%. - Plus and minus in front of one value, like
+"4". - Adding or taking away one with
++and--. - Shortcuts that update a variable, like
+=. - Which operator runs first.
- What
+does when one side is a string.
The arithmetic operators: + - * / % **
REAL OUTPUTSMost of these symbols work like the buttons on a calculator. Three of them need a note:
*means multiply.**means "to the power of".2 ** 3is 2 × 2 × 2, which is 8. This is called exponentiation.%does not mean percent. It gives the remainder: what is left over after you divide.
console.log(8 + 3);console.log(8 - 3);console.log(8 * 3);console.log(8 / 3);console.log(8 % 3);console.log(2 ** 3);Each line prints one answer: 11, 5, 24, about 2.67, 2, and 8. Now look at a small total. Line 4 multiplies the tea price by the number of teas. Then it adds the delivery fee. The answer is 14. Just like in school math, JavaScript works out 3 * 4 first and then adds 2.
const teaPrice = 3;const teaCount = 4;const delivery = 2;const total = teaPrice * teaCount + delivery;console.log(total);The table shows each operator once. Read each row as: this symbol does this job, so this example gives this answer.
| Symbol | What it does | Example | What you get |
|---|---|---|---|
| + | It adds. | 8 + 3 | 11 |
| - | It subtracts. | 8 - 3 | 5 |
| * | It multiplies. | 8 * 3 | 24 |
| / | It divides. | 8 / 3 | 2.6666666666666665 |
| % | It gives the remainder. | 8 % 3 | 2 |
| ** | It raises to a power. | 2 ** 3 | 8 |
Division can give a decimal. 10 / 4 is 2.5, not 2. If you need a whole number, pick a rounding rule on purpose. Math is a set of math tools built into JavaScript. Three of them round:
Math.trunccuts off the decimal part.Math.floorrounds down.Math.roundrounds to the nearest whole number.
const pizzas = 10;const guests = 4;const share = pizzas / guests;console.log(share);console.log(Math.floor(share));console.log(Math.round(share));Line 3 divides and gets 2.5. Line 4 prints it. Line 5 uses Math.floor and prints 2, because you can't give each guest more whole pizzas than you have. Line 6 uses Math.round and prints 3. That is the nearest whole number, but 4 guests × 3 pizzas is more than 10. Pick the rule that fits what you are building.
The Numbers & math lesson showed Infinity and NaN ("Not a Number"). Operators can give them too: 5 / 0 is Infinity, and 0 / 0 is NaN.
Decimals are not always exact: 0.1 + 0.2 is 0.30000000000000004. For simple money totals, count in whole cents instead. 30 cents plus 20 cents is exactly 50 cents.
const teaCents = 30;const snackCents = 20;const totalCents = teaCents + snackCents;console.log(totalCents);Lines 1 and 2 store two prices in cents. Line 3 adds two whole numbers, so the answer, 50, is exact.
% gives the leftover: the remainder
INTERACTIVEThink of candy. You share 7 candies equally between 3 kids. Each kid gets 2 candies, and 1 candy is left. That leftover is 7 % 3.
7 % 3 gives you that leftover: 1.You hand out candies until you can't give every kid one more. The candies still in your hand are the leftover.
- In real life: 7 candies
- In JavaScript: The left number,
7 - In real life: 3 kids
- In JavaScript: The right number,
3 - In real life: 1 candy left over
- In JavaScript: The remainder,
7 % 3
Remainder answers one question: after you make as many equal groups as you can, what is left? That is handy for two jobs: checking if a number is even, and going back to the start of a list.
With negative numbers, the answer takes the sign of the left number. So -7 % 3 is -1, and 7 % -3 is 1.
Sometimes you want an answer that is never negative. Think of a clock: one hour before 0 o'clock should be 11, not -1. Math calls this always-positive version modulo. JavaScript has no modulo operator, so use this formula when b is positive: ((a % b) + b) % b. Try both below.
const a = -7;const b = 3;console.log(a % b);console.log(((a % Math.abs(b)) + Math.abs(b)) % Math.abs(b));- a % b
- -1
- ((a % b) + b) % b
- 2
-7 % 3 is -1. The always-positive formula, using 3, gives 2.
%, which gives the remainder. Line 4 uses the always-positive formula, which suits clocks, carousels, and positions in a list. Math.abs(b) drops the minus sign from b, so the formula works for a negative b too.Plus and minus in front of one value
Most operators in this lesson sit between two values. A unary operator works on just one value. You write it in front of the value:
- Unary plus,
+value, turns the value into a number. - Unary minus,
-value, turns the value into a number and then flips its sign.
console.log(+"42");console.log(+"");console.log(+true);console.log(-"5");console.log(-(-3));console.log((-2) ** 2);The cards below explain each line of that code, in order.
Unary plus is most useful for text from a form field. A form field always gives you a string, even when the user types a number. In the next example, line 2 turns the text "4" into the number 4, so line 3 prints 5. Line 4 prints NaN, because "tea" is not a number. Check numbers from users before you use them in important math.
const seatsText = "4";const seats = +seatsText;console.log(seats + 1);console.log(+"tea");JavaScript does not allow -2 ** 2. It stops with a SyntaxError, which is an error for code it can't read. The reason: it can't tell if you mean "square -2" or "square 2, then make it negative". Put round brackets around the negative number: (-2) ** 2 is 4.
++ and --: change by one
STEP THROUGHcount++ adds one to count. count-- takes one away. These are called the increment and decrement operators.
Here is the tricky part. count++ does two things at once: it changes the variable, and it gives a value. Which value it gives depends on where you write the ++:
- Postfix,
count++, has the++after the name. It gives the old value, then changes the variable. - Prefix,
++count, has the++before the name. It changes the variable first, then gives the new value.
At a bank, you take a paper ticket with the number the machine shows. Then the machine moves to the next number. Postfix works like that: you get the old number. Prefix moves the machine first, so you get the new number.
- In real life: Take the ticket with the number showing now
- In JavaScript: Postfix
ticket++gives the old value - In real life: The machine moves to the next number
- In JavaScript: The variable goes up by one after its value is used
- In real life: The machine moves first, then you take a ticket
- In JavaScript: Prefix
++ticketchanges first, then gives the new value
ticket from 5 to 6. Postfix ticket++ gives you the old number, 5. Prefix ++ticket changes the number first, so it gives you 6.Compare postfix and prefix. Postfix gives the old value first. Prefix adds one first.
script
const handedOut = ticket++;console.log(handedOut, ticket);In everyday code, write count += 1 unless you need the value that ++ gives. It is clearer, because it only says one thing: "add one to this variable."
let seats = 3;const lastSeat = seats--;console.log(lastSeat, seats);Line 1 starts with 3 free seats. Line 2 does two things: lastSeat gets the old value, 3, and then seats drops to 2. So line 3 prints 3 2. Prefix --seats would lower the count first and give 2, just like prefix ++ gives the new value.
Compound assignment: update a variable in one step
INTERACTIVEThe Variables lesson showed =. It stores the value on the right in the variable on the left. Compound assignment is a shortcut that also uses the old value. total += 5 means total = total + 5: read total, add 5, and store the answer back in total.
total += 5 is short for total = total + 5. JavaScript reads the old value, 10, adds 5, and puts 15 back in the same box.The same shortcut works with the other operators too: -=, *=, /=, %=, and **=. For example, total *= 2 means total = total * 2.
You don't empty a coin jar, count the coins, add five, and fill the jar again. You just drop five more coins in. Compound assignment lets your code say it that short way too.
- In real life: A jar with 10 coins in it
- In JavaScript: A variable
totalholding 10 - In real life: Drop 5 more coins in
- In JavaScript:
total += 5 - In real life: The jar now holds 15 coins
- In JavaScript:
totalnow holds 15
let total = 10;total += 5;total *= 2;total %= 6;total **= 3;console.log(total);After let total = 10, total is 10. Each shortcut reads the old value, works out a new one, and stores it back.
+ also joins strings, so += can add text to the end of a string. message += "!" adds an exclamation mark and stores the new string back in message.
let message = "Hi";message += ", Asha";console.log(message);Line 1 stores "Hi". Line 2 reads it, adds ", Asha" to the end, and stores "Hi, Asha" back in message. Line 3 prints Hi, Asha. This is useful when you build a message in steps. For one finished sentence, a template literal is often easier to read. You'll see one in the section about + with strings.
Which operator runs first
STEP THROUGHJavaScript does not just read operators from left to right. Like school math, it follows an order. This order is called precedence:
**runs first.- Then
*,/, and%. - Then
+and-.
Round brackets ( ) change the order: whatever is inside them runs first. This is called grouping.
const price = 10;const discount = 2;const quantity = 3;console.log((price - discount) * quantity);Line 4 has round brackets around price - discount. So JavaScript works out 10 - 2, which is 8, first. Then it multiplies by 3 and prints 24. Without the brackets, * would run first: 10 - 2 * 3 is 10 - 6, which is 4. Add brackets whenever they show what you mean. Clear code is worth a few extra characters.
Guess the final number first. Then step through each small calculation JavaScript does.
script
console.log(result);Compare the first two choices. 2 + 3 * 4 ** 2 is 50, but (2 + 3) * 4 ** 2 is 80. The third choice shows one more rule: two ** in a row run from right to left. So 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 2 ** 9, or 512. This right-to-left rule is called being right-associative.
+ with strings: add or join?
SORTERWith two numbers, + adds. If either side is a string, + joins the two sides as text. Joining strings is called concatenation. JavaScript works through a chain of + from left to right, one pair at a time. So the same pieces in a different order can give a different answer.
console.log("3" + 4 + 5);console.log(3 + 4 + "5");console.log("Total: " + (2 + 3));- Line 1:
"3" + 4joins to"34". Then"34" + 5joins to"345". - Line 2:
3 + 4adds to7first. Then7 + "5"joins to"75". - Line 3: the round brackets run first, so
2 + 3is5. Then the label joins with it:"Total: 5".
+ works from left to right, one pair at a time. Top row: a string comes first, so every + joins text. Bottom row: the first + sees two numbers and adds them. Only the second + joins text.const itemCount = 3;console.log(`Items: ${itemCount}`);This prints Items: 3. A template literal is a string written between backticks, the ` character. Inside it, ${itemCount} puts the value of itemCount into the text. You don't have to think about a chain of +. Use + for math and short joins. Use a template literal when a sentence has values in it.
3 + 4"3" + 4"8" - 3"Total: " + (2 + 3)+"42"2 + "3" + 4
Sort each expression by the kind of value it gives. Do the round brackets first, then read from left to right.
Where you will use this
Operators show up whenever a web page works something out. For example:
- the total price in a shopping cart
- a progress bar's percentage
- an average star rating
- shading every other row of a table
- a slideshow that goes back to the first slide after the last one
- a game score, or a sentence with a number in it
const subtotal = 19.99 + 4.5;const isEven = n % 2 === 0;const average = (a + b) / 2;const wrapped = ((index % length) + length) % length;const label = "Total: " + subtotal;In plain words, line by line:
- Add two prices.
isEvenistruewhenndivides by 2 with nothing left over.===checks if two values are equal; the next lesson covers it.- Add first, because of the round brackets, then divide by 2 to get the average.
- Keep
indexbetween 0 andlength - 1, even when it is negative. - Join a label with a number to make display text.
You can read bigger programs the same way. Find the expression, work out its value, then check if the value gets stored.
Common misconceptions
"% always gives a positive answer."
No. % gives the remainder, which takes the sign of the left number. -7 % 3 is -1.
"Dividing two whole numbers gives a whole number."
No. 10 / 4 is 2.5. Round on purpose if you need a whole number.
"x++ and ++x always do the same thing."
Both add one to x. But x++ gives the old value, and ++x gives the new one.
"= checks if two values are equal."
No. = stores a value. To check if two values are equal, you use ===, which the next lesson covers.
"+ always adds."
If either side is a string, + joins the two sides as text instead.
These operators look alike but do different jobs. Read each row as: when you write this, here is what happens.
| When you write | What happens | Example |
|---|---|---|
= | It stores a value in a variable. | total = 10 |
+= | It uses the old value to work out a new one, then stores it. | total += 5 |
% | It gives the remainder, with the sign of the left number. | -7 % 3 → -1 |
++x | It adds one first, then gives the new value. | ++x |
x++ | It gives the old value, then adds one. | x++ |
+ with a string | It joins the two sides as text. | "3" + 4 → "34" |
Practice: arithmetic and assignment
6 EXERCISESFollow points one line at a time. What does the program print?
let points = 10;
points += 5;
points *= 2;
console.log(points);points += 5 stores 15. points *= 2 stores 30. So the program prints 30.
Write an expression that is true when n is even.
n % 2 === 0A whole number is even when the remainder after dividing by 2 is 0.
This code should give the average of a and b. But it only halves b and then adds a. What expression fixes it?
const average = a + b / 2;const a = 10;
const b = 20;
console.log((a + b) / 2);Write (a + b) / 2. The round brackets make JavaScript add first, then divide.
A carousel is a row of slides you move through. This one has 5 slides, at positions 0 to 4. Going back from position 0 gives -1. Work out the formula in your head. What position prints?
const index = -1;
const length = 5;
console.log(((index % length) + length) % length);const index = -1;
const length = 5;
console.log(((index % length) + length) % length);-1 % 5 is -1. Adding 5 gives 4. 4 % 5 is still 4. So the carousel goes to position 4, the last slide.
What three values does console.log print?
let a = 5;
const b = a++;
const c = ++a;
console.log(b, a, c);b gets 5, and a becomes 6. ++a makes a 7 and gives 7 to c. So the program prints 5 7 7.
A cart starts with items worth 18. Add a delivery fee of 4. Then take off a coupon worth 2. Follow each line, then write the exact text the program prints.
let cartTotal = 18;
cartTotal += 4;
cartTotal -= 2;
console.log("Total: " + cartTotal);let cartTotal = 18;
cartTotal += 4;
cartTotal -= 2;
console.log("Total: " + cartTotal);The cart starts at 18. Adding 4 makes 22. Taking off 2 makes 20. The last line joins the label with that number, so it prints Total: 20.
Quiz: check your understanding
8 QUESTIONSGuess the answer before you choose. Each answer explains the rule it tests.
Question 1 of 8Which operator runs first? What does this print?
Read the code, then predictconsole.log(2 + 3 * 4);Choose an answer to see the explanation.
Question 2 of 8Which sentence about
%is true in JavaScript?Choose an answer to see the explanation.
Question 3 of 8What does this chain of
+print?Read the code, then predictconsole.log("3" + 4 + 5);Choose an answer to see the explanation.
Question 4 of 8What does postfix
++print here?Read the code, then predictlet a = 5; const b = a++; console.log(b, a);Choose an answer to see the explanation.
Question 5 of 8What does plus in front of a string do here?
Read the code, then predictconsole.log(+"42");Choose an answer to see the explanation.
Question 6 of 8What does
**=print here?Read the code, then predictlet total = 2; total **= 3; console.log(total);Choose an answer to see the explanation.
Question 7 of 8Which expression gives the average of
aandb?Choose an answer to see the explanation.
Question 8 of 8What does this program print?
Read the code, then predictlet price = 10; price += 5; price *= 2; console.log(price);Choose an answer to see the explanation.
Key takeaways
+ - * / % **work out values.%gives the remainder, which can be negative.- Unary plus turns a value into a number. Unary minus also flips the sign. Put round brackets around a negative number before
**. ++and--change a variable by one. Postfix gives the old value; prefix gives the new one.- Compound assignment, like
+=, reads the old value, works out a new one, and stores it back. - Precedence decides which operator runs first. Round brackets make the order you mean clear.
+adds numbers, but joins text when either side is a string.
Remember the one-liner.
Operators work out values; assignment stores them; round brackets and strings explain most surprises.
Up next: Comparisons. You'll ask whether two values are equal, or which one is bigger.