completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Arithmetic & assignment

Use JavaScript's arithmetic operators, assignment shortcuts, increments, precedence rules, and string-plus behavior without surprises.

By the end, you can
  • 01
    Do math with operatorsUse + - * / % **, and plus or minus in front of one value, and know what each gives.
  • 02
    Update variablesRead ++, --, and shortcuts like += as changes to a variable.
  • 03
    Know 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.

The main idea

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?

Real-life analogyOperators are calculator buttons

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 OUTPUTS

Most of these symbols work like the buttons on a calculator. Three of them need a note:

  • * means multiply.
  • ** means "to the power of". 2 ** 3 is 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.
One line for each operatorPop out in the code editor (opens in a new tab)JavaScript
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.

Four teas plus deliveryPop out in the code editor (opens in a new tab)JavaScript
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.

What each arithmetic operator gives
SymbolWhat it doesExampleWhat you get
+It adds.8 + 311
-It subtracts.8 - 35
*It multiplies.8 * 324
/It divides.8 / 32.6666666666666665
%It gives the remainder.8 % 32
**It raises to a power.2 ** 38

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.trunc cuts off the decimal part.
  • Math.floor rounds down.
  • Math.round rounds to the nearest whole number.
Share 10 pizzas between 4 guestsPop out in the code editor (opens in a new tab)JavaScript
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.

Two surprises with division and decimals

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.

Add money in whole centsPop out in the code editor (opens in a new tab)JavaScript
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

INTERACTIVE

Think 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.

Seven candies shared by three kids. Kid 1, kid 2, and kid 3 each get 2 candies. 1 candy is left over, and 7 % 3 gives that leftover, 1.3 kids, 2 candies each2 candies2 candies2 candieskid 1kid 2kid 3left over1 candy7 % 3 is 1
Share 7 candies between 3 kids. Each kid gets 2, and 1 candy is left over. 7 % 3 gives you that leftover: 1.
Real-life analogyRemainder is leftover candy

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.

Remainder or always-positive answer
Remainder, then the always-positive formulaPop out in the code editor (opens in a new tab)JavaScript
const a = -7;const b = 3;console.log(a % b);console.log(((a % Math.abs(b)) + Math.abs(b)) % Math.abs(b));
Try valuesb must not be 0
a % b
-1
((a % b) + b) % b
2
Try it yourself

-7 % 3 is -1. The always-positive formula, using 3, gives 2.

Line 3 uses %, 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.
Plus and minus in front of one valuePop out in the code editor (opens in a new tab)JavaScript
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.

+"42" → 42A string of digits becomes a number.
+"" → 0An empty string becomes 0.
+true → 1true becomes 1, and false becomes 0.
-"5" → -5It becomes a number, then the sign flips.
-(-3) → 3Flipping a negative number gives a positive one.
(-2) ** 2 → 4The round brackets keep -2 together.

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.

Turn the seat text into a numberPop out in the code editor (opens in a new tab)JavaScript
const seatsText = "4";const seats = +seatsText;console.log(seats + 1);console.log(+"tea");
Why not -2 ** 2?

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 THROUGH

count++ 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.
Real-life analogyA ticket machine at the bank

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 ++ticket changes first, then gives the new value
Left: ticket++. The box ticket changes from 5 to 6, but the expression gives the old value, 5. Right: ++ticket. The box ticket changes from 5 to 6 first, and the expression gives the new value, 6.ticket++5 → 6ticket5gives the old value++ticket5 → 6ticket6gives the new value
Both change ticket from 5 to 6. Postfix ticket++ gives you the old number, 5. Prefix ++ticket changes the number first, so it gives you 6.
The bank ticket machine: postfix or prefix
Step 0 of 4Ready
Your turn: follow the blue line

Compare postfix and prefix. Postfix gives the old value first. Prefix adds one first.

Running in
  1. script
Next: line 1
const handedOut = ticket++;console.log(handedOut, ticket);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Which version should line 2 use?
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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."

Postfix -- gives the old seat countPop out in the code editor (opens in a new tab)JavaScript
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

INTERACTIVE

The 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. Before, the box total holds 10. JavaScript reads 10, adds 5, and puts 15 back in the same box total.total += 510totalbefore+ 515totalafter
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.

Real-life analogyCompound assignment is adding to a jar

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 total holding 10
In real life: Drop 5 more coins in
In JavaScript: total += 5
In real life: The jar now holds 15 coins
In JavaScript: total now holds 15
A running total, one shortcut at a time
Running totalPop out in the code editor (opens in a new tab)JavaScript
let total = 10;total += 5;total *= 2;total %= 6;total **= 3;console.log(total);
What total holds nowstart
10let total = 10
Step 1 of 5start

After let total = 10, total is 10. Each shortcut reads the old value, works out a new one, and stores it back.

Click a button to jump to that line. 30 % 6 is 0, because 6 goes into 30 exactly. Then 0 ** 3 is still 0, so the program prints 0.
+= can build strings too

+ 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.

Add a name to a greetingPop out in the code editor (opens in a new tab)JavaScript
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 THROUGH

JavaScript does not just read operators from left to right. Like school math, it follows an order. This order is called precedence:

  1. ** runs first.
  2. Then *, /, and %.
  3. Then + and -.

Round brackets ( ) change the order: whatever is inside them runs first. This is called grouping.

Take off the discount, then multiplyPop out in the code editor (opens in a new tab)JavaScript
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.

Which operator runs first?
Step 0 of 4Ready
Your turn: follow the blue line

Guess the final number first. Then step through each small calculation JavaScript does.

Running in
  1. script
Next: line 1
console.log(result);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Pick an expression to step through

Picking a new expression starts again from line 1. Guess the answer before you step.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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?

SORTER

With 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.

The same pieces in a different orderPop out in the code editor (opens in a new tab)JavaScript
console.log("3" + 4 + 5);console.log(3 + 4 + "5");console.log("Total: " + (2 + 3));
  • Line 1: "3" + 4 joins to "34". Then "34" + 5 joins to "345".
  • Line 2: 3 + 4 adds to 7 first. Then 7 + "5" joins to "75".
  • Line 3: the round brackets run first, so 2 + 3 is 5. Then the label joins with it: "Total: 5".
Two rows. Top row: "3" + 4 + 5 joins "3" and 4 into "34", then joins 5 to get "345". Bottom row: 3 + 4 + "5" adds 3 and 4 to get 7, then joins "5" to get "75"."3" + 4 + 5joins"34" + 5joins"345"3 + 4 + "5"adds7 + "5"joins"75"
+ 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.
Use a template literal for display textPop out in the code editor (opens in a new tab)JavaScript
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.

Number result or string result?
  • 3 + 4
  • "3" + 4
  • "8" - 3
  • "Total: " + (2 + 3)
  • +"42"
  • 2 + "3" + 4
Try it yourself
0 of 6 correct

Sort each expression by the kind of value it gives. Do the round brackets first, then read from left to right.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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
Five everyday usesPop out in the code editor (opens in a new tab)JavaScript
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:

  1. Add two prices.
  2. isEven is true when n divides by 2 with nothing left over. === checks if two values are equal; the next lesson covers it.
  3. Add first, because of the round brackets, then divide by 2 to get the average.
  4. Keep index between 0 and length - 1, even when it is negative.
  5. 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.

Operators that look alike
When you writeWhat happensExample
=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
++xIt adds one first, then gives the new value.++x
x++It gives the old value, then adds one.x++
+ with a stringIt joins the two sides as text."3" + 4 → "34"

Practice: arithmetic and assignment

6 EXERCISES
Exercise 1 · Warm-upPredict the updates to points

Follow points one line at a time. What does the program print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
let points = 10;
points += 5;
points *= 2;
console.log(points);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeEven or odd

    Write an expression that is true when n is even.

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix the average bug

      This code should give the average of a and b. But it only halves b and then adds a. What expression fixes it?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const average = a + b / 2;

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeLoop a carousel back to the end

        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?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const index = -1;
        const length = 5;
        console.log(((index % length) + length) % length);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengePrefix and postfix together

          What three values does console.log print?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          let a = 5;
          const b = a++;
          const c = ++a;
          console.log(b, a, c);

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeUpdate a cart total

            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.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            let cartTotal = 18;
            cartTotal += 4;
            cartTotal -= 2;
            console.log("Total: " + cartTotal);

            Answer, then press Check. Spacing and letter case don’t matter.

              Quiz: check your understanding

              8 QUESTIONS

              Guess the answer before you choose. Each answer explains the rule it tests.

              Lesson quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Which operator runs first? What does this print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log(2 + 3 * 4);

                Choose an answer to see the explanation.

              2. Question 2 of 8Which sentence about % is true in JavaScript?

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this chain of + print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log("3" + 4 + 5);

                Choose an answer to see the explanation.

              4. Question 4 of 8What does postfix ++ print here?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                let a = 5;
                const b = a++;
                console.log(b, a);

                Choose an answer to see the explanation.

              5. Question 5 of 8What does plus in front of a string do here?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log(+"42");

                Choose an answer to see the explanation.

              6. Question 6 of 8What does **= print here?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                let total = 2;
                total **= 3;
                console.log(total);

                Choose an answer to see the explanation.

              7. Question 7 of 8Which expression gives the average of a and b?

                Choose an answer to see the explanation.

              8. Question 8 of 8What does this program print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                let 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.

              CompleteFrontend Clear concepts. Working examples.