cf.completefrontendCode editorOpen lab
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
    Compute with operatorsUse + - * / % **, unary plus, and negation accurately.
  • 02
    Update values safelyRead ++, --, and compound assignment as value changes.
  • 03
    Predict orderUse precedence, parentheses, and string + rules to predict results.

Operators compute values; assignment stores them

JavaScript expressions are little machines that produce values. In the previous lessons you met variables, numbers, strings, and conversion. This lesson is where those pieces start moving: operators combine values, and assignment stores the result for the next line.

An operator is a symbol with a job. In 2 + 3, the + operator combines the operands 2 and 3. In total += 5, the operator reads total, adds 5, and stores the new value back.

The short definition

Arithmetic operators compute values. Assignment operators store values. When code surprises you, ask two questions: what value does this expression produce? and where is that value stored?

Real-life analogyOperators are calculator buttons

A calculator button does one clear operation with the numbers around it. JavaScript operators are similar, except their answers can feed directly into another operator before you ever see them.

In real life: Pressing × on a calculator
In JavaScript: Using * between two values
In real life: Pressing = to display a result
In JavaScript: An expression producing a value
In real life: Writing the answer in a notebook
In JavaScript: Assignment storing the result in a variable

Where the analogy stops: A calculator button usually shows the answer immediately. JavaScript expressions can be nested inside bigger expressions before anything is printed or stored.

We will move in the same order you will use in real code: basic arithmetic, remainder, unary operators, increments, compound assignment, precedence, and the special string behavior of +.

The arithmetic operators: + - * / % **

REAL OUTPUTS

JavaScript uses familiar calculator symbols, with two programming symbols to remember: * means multiply, and ** means exponentiation, or “to the power of.” The % operator is not “percent” in JavaScript expressions; it gives a remainder.

Six arithmetic operatorsPop 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);
Arithmetic operators
OperatorNameExampleResult
+Addition8 + 311
-Subtraction8 - 35
*Multiplication8 * 324
/Division8 / 32.6666666666666665
%Remainder8 % 32
**Exponentiation2 ** 38

Division is not integer division. 10 / 4 is 2.5. If you need a whole number, choose the rounding rule you mean: Math.trunc cuts off the decimal, Math.floor rounds down, and Math.round rounds to the nearest integer.

Division edge cases

Numbers & math already introduced Infinity and NaN. Operators can produce them too: 5 / 0 is Infinity, and 0 / 0 is NaN.

% is remainder, not modulo

INTERACTIVE

The easiest positive example is candy. If 7 candies are shared equally among 3 kids, each kid gets 2 candies and 1 candy is left. That leftover is 7 % 3.

Real-life analogyRemainder is leftover candy

Remainder answers “what is left after taking as many equal groups as possible?” That makes it great for even/odd checks and wrapping indexes, as long as you remember the negative case.

In real life: 7 candies
In JavaScript: The dividend, 7
In real life: 3 kids
In JavaScript: The divisor, 3
In real life: 1 candy left over
In JavaScript: The remainder, 7 % 3

Where the analogy stops: Candy sharing explains positive whole numbers. With negative values, JavaScript follows a precise remainder rule: the sign follows the dividend.

JavaScript % keeps the sign of the left operand. So -7 % 3 is -1, while 7 % -3 is 1. For clock or carousel wrapping, you often want an always-positive modulo. Use ((a % b) + b) % b when b is positive.

Remainder vs modulo explorer
The two calculationsPop out in the code editor (opens in a new tab)JavaScript
const a = -7;const b = 3;console.log(a % b);console.log(((a % b) + b) % b);
Try valuesNon-zero divisor
a % b
-1
((a % b) + b) % b
2
Try it yourself

-7 % 3 is -1. For positive wrapping by 3, the modulo formula gives 2.

JavaScript % is the remainder operator. The modulo row uses a formula that is helpful for clocks, carousels, and indexes.

Unary plus and negation

Most operators in this lesson sit between two values. Unary operators use one value. Unary plus converts a value to a number; unary minus converts and then flips the sign.

Unary operatorsPop 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);
+"42" → 42A numeric string becomes a number.
+"" → 0The empty string converts to 0.
+true → 1Booleans follow number conversion.
-"5" → -5Convert, then negate.
-(-3) → 3Negating a negative gives a positive.
(-2) ** 2 → 4Parentheses make the negative base explicit.
Why not -2 ** 2?

JavaScript treats -2 ** 2 as a syntax error. Put the negative base in parentheses: (-2) ** 2. The tests for this lesson prove both the error and the valid result.

++ and --: change by one

STEP THROUGH

count++ means “increase count by one.” count-- means “decrease by one.” The part beginners trip over is that increment and decrement are expressions: they both change the variable and produce a value.

Real-life analogyPostfix is a token machine

At a hospital or bank, take the number showing now and the machine moves on. Postfix gives the old number first; prefix moves to the next number first.

In real life: Take the number showing now
In JavaScript: Postfix ticket++ produces the old value
In real life: The machine moves to the next number
In JavaScript: The variable changes after the value is used
In real life: Move it first, then take the number
In JavaScript: Prefix ++ticket changes first

Where the analogy stops: A token machine does not return values into variables. It only shows old-value-first versus new-value-first timing.

Prefix or postfix ticket machine
Step 0 of 4Ready
Your turn: follow the blue line

Compare postfix and prefix. One gives the old value first; the other increments first.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const handedOut = ticket++;console.log(handedOut, ticket);
CallStoreChangeResultRun = next line. 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, prefer count += 1 unless you specifically need the expression value of prefix or postfix. It is clearer because it only says “update this variable.”

Compound assignment: add to the jar

INTERACTIVE

The Variables lesson introduced =: store the value on the right into the name on the left. Compound assignment keeps the same idea but uses the old value too. total += 5 means total = total + 5. The same pattern works for -=, *=, /=, %=, and **=.

Real-life analogyCompound assignment is adding to a jar

Instead of saying “take the jar, count it, add five, and label the jar again,” you say “add five to the jar.” Compound assignment is that kind of shorthand.

In real life: A jar currently holding 10 coins
In JavaScript: A variable total currently holding 10
In real life: Add 5 coins to the jar
In JavaScript: total += 5
In real life: Put the jar back with 15 coins
In JavaScript: Store the new value back in total

Where the analogy stops: A jar changes physically. JavaScript variables hold values; for primitive numbers, the old number is replaced by a new number.

Compound assignment total
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);
Value of totalstart
10let total = 10
Step 1 of 5start

let total = 10 leaves total as 10. Each shortcut reads the old value, computes, and stores back.

This is a guided display of one real program. The tests run the same source and confirm the final output is 0.
+= can build strings too

Because + also joins strings, message += "!" appends an exclamation mark and stores the new string back in message.

Precedence and grouping

STEP THROUGH

JavaScript does not simply read every operator from left to right. Like school arithmetic, it has an order of operations: exponentiation first, then multiplication/division/remainder, then addition and subtraction. Parentheses are your override when the human meaning should happen first.

Precedence visualizer
Step 0 of 4Ready
Your turn: follow the blue line

Predict the final number, then step through the sub-expressions JavaScript evaluates.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log(result);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the expression to replay

Changing the expression starts a fresh replay. Predict the result before stepping.

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.

Notice that 2 + 3 * 4 ** 2 is 50, but (2 + 3) * 4 ** 2 is 80. Also, ** is right-associative: 2 ** 3 ** 2 is 2 ** (3 ** 2), or 512.

+ with strings: addition or concatenation?

SORTER

With two numbers, + adds. If either side is a string, + joins text. The result then keeps moving left to right. That is why the same pieces can produce different answers.

String plus is left to rightPop 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));

"3" + 4 + 5 becomes "34" + 5, then "345". But 3 + 4 + "5" adds first, producing 7 + "5", then "75". Parentheses let you choose: "Total: " + (2 + 3) is "Total: 5".

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 type of value it produces. Read left to right after precedence.

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 anywhere an interface computes: totals in a cart, a progress percentage, an average rating, alternating rows, a carousel index, a game score, or a sentence that includes a number.

Practical operator patternsPop 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;

These examples are short because operators are vocabulary. Once you can read them accurately, larger programs become easier to trace: find the expression, compute the value, then see whether anything is stored.

Common misconceptions

“% is modulo, so it is always positive.”

In JavaScript it is remainder. -7 % 3 is -1.

“/ does integer division when both inputs are integers.”

No. 10 / 4 is 2.5. Round on purpose if you need an integer.

“x++ and ++x are interchangeable everywhere.”

They both update x, but they produce different expression values.

“= checks equality.”

= assigns. Comparisons such as === come next lesson.

“+ always adds.”

With a string on either side, + concatenates text.

Similar-looking operations
Looks likeActually meansExample
=Store a valuetotal = 10
+=Compute with old value and storetotal += 5
%Remainder-7 % 3 → -1
++xIncrement first, produce new value++x
x++Produce old value, increment afterx++
+ with stringsConcatenate"3" + 4 → "34"

Practice: arithmetic and assignment

5 EXERCISES
Exercise 1 · Warm-upPredict the compound updates

Trace points line by line. 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

      The code should average a and b, but it only halves b. 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 · ChallengeWrap a carousel index

        Run the wrapping formula mentally. What index 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

          Predict the three values printed by console.log.

          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.

            Quiz: check your understanding

            7 QUESTIONS

            Predict before you choose. Each answer explains the exact operator rule being tested.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does the precedence expression 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 7Which statement about % is correct in JavaScript?

              Choose an answer to see the explanation.

            3. Question 3 of 7What does the string-plus chain 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 7What does postfix increment print?

              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 7What does unary plus 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 7What does exponentiation assignment print?

              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 7Which expression fixes an average calculation for a and b?

              Choose an answer to see the explanation.

            Key takeaways

            • + - * / % ** compute values; % is remainder, not always-positive modulo.
            • Unary plus converts to number; unary minus negates. Parenthesize negative bases before **.
            • ++ and -- update by one; prefix and postfix differ when their value is used.
            • Compound assignment reads the old value, computes, and stores back.
            • Precedence decides the default order; parentheses make your intent obvious.
            • + adds numbers but concatenates when a string is involved.

            Remember the one-liner.
            Operators compute values; assignment stores them; parentheses and strings decide many surprises.

            Up next: Comparisons, where you ask whether values are equal, larger, smaller, or safely comparable.

            CompleteFrontend Clear concepts. Working examples.