JavaScript • Syntax and Core Types

Assignment Operators — Use assignment operators (+=, -=, etc.)

Master the shorthand operators that make updating variables faster, cleaner, and less error-prone in JavaScript.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 10 figures

SECTION 1

Historical Context & Motivation

Every programming language needs a way to store values and update them. The simplest tool for the job is the assignment operator (=), which places a value into a variable. But as programmers wrote more code, they noticed a repeating pattern: they were constantly writing things like score = score + 10. That kind of repetition led language designers to invent compound assignment operators — shortcuts like += that combine a math operation with assignment in a single step.

1972 • C Language Introduces Compound Assignment

Dennis Ritchie's C language formalized operators like += and -=, setting a standard that nearly every language after it would follow.

1995 • JavaScript Is Born

Brendan Eich created JavaScript in just 10 days, borrowing C-style compound assignment operators to give web developers concise syntax for updating variables.

2009 • ES5 Standardizes Behavior

ECMAScript 5 clarified how assignment operators interact with type coercion and strict mode, making their behavior more predictable across browsers.

2021 • Logical Assignment Operators Added

ES2021 introduced &&=, ||=, and ??=, expanding the compound assignment family to include logical operations.

The core question these operators answer is simple: How can we update a variable's value without writing its name twice? This may seem like a small convenience, but in real-world programs where variables are updated thousands of times, compound assignment operators reduce errors and make code significantly easier to read.

SECTION 2

Core Principles & Definitions

Before diving into each operator, you need to understand three foundational ideas. The basic assignment operator (=) evaluates the expression on the right side and stores the result in the variable on the left. A compound assignment operator combines that storage step with an arithmetic or logical operation so you can do both at once. Each compound operator follows a predictable pattern: x op= y means the same thing as x = x op y.

1

Simple Assignment (=)

Stores a value in a variable. let x = 5 puts the number 5 into x. This is the foundation all other assignment operators build on.
2

Compound Pattern (op=)

Reads the current value, performs an operation, and writes the result back. x += 3 is shorthand for x = x + 3.
3

Right-Side Evaluation First

JavaScript always evaluates the right side of the operator before performing the assignment. In x += 2 * 3, the multiplication happens first, then 6 is added to x.
4

Type Coercion Matters

JavaScript may convert types automatically. Using += with a string and a number concatenates them instead of adding. Be mindful of your variable types.
✦

KEY TAKEAWAY

Think of compound assignment operators like a self-checkout machine at a store. Instead of taking your total, handing it to someone else, adding a new item, and getting the total back (the long way), the machine keeps a running total and just adds each item as you scan it. += is your "scan and add" button — it reads what's already there and updates it in one step.

SECTION 3

Visual Explanation

How x += 3 Works Under the Hood

The Long Way vs. The ShorthandLONG FORMx = x + 31. Read x2. Add 3 to the value3. Store result back in xSHORTHANDx += 3Same 3 steps,one concise expression.✓ Less repetition, fewer bugsequivalentStep-by-Step Flow: x += 3 (where x is 7)STEP 1: READx → 7STEP 2: COMPUTE7 + 3 = 10STEP 3: STOREx ← 10After this line runs, x holds the value 10.
The top half compares the long-form assignment (x = x + 3) with the compound shorthand (x += 3). The bottom flow shows the three internal steps: read the current value, compute the result, and store it back.

Notice how the shorthand version eliminates the need to type the variable name x twice. This matters more than you might think — when variable names are long (like totalStudentScore), the compound operator keeps your code concise and reduces the chance of a typo causing a bug. The underlying logic is identical either way: JavaScript reads the old value, performs the operation, and stores the new result.

SECTION 4

How Each Operator Works

JavaScript provides several compound assignment operators. Each follows the same pattern — perform an operation and assign the result — but with a different arithmetic or bitwise operation built in. Let's define the core ones you will use most often.

ADDITION ASSIGNMENT

x+=y→x=x+yx += y → x = x + y

Adds y to x and stores the sum. If either operand is a string, it performs concatenation instead.

SUBTRACTION ASSIGNMENT

x−=y→x=x−yx −= y → x = x − y

Subtracts y from x and stores the difference.

MULTIPLICATION ASSIGNMENT

x×=y→x=x×yx ×= y → x = x × y

Written as *= in code. Multiplies x by y and stores the product.

DIVISION ASSIGNMENT

x/=y→x=x/yx /= y → x = x / y

Divides x by y and stores the quotient. Be careful — dividing by zero produces Infinity in JavaScript.

REMAINDER (MODULO) ASSIGNMENT

xx %= y → x = x % y

Divides x by y and stores only the remainder. Useful for tasks like checking if a number is even (n % 2 === 0).

⚠

Watch Out: += With Strings

If x is a string, += concatenates rather than adds. For example, let msg = "Hello"; msg += " World"; results in "Hello World". This is handy for building strings, but it can trip you up if you accidentally mix strings and numbers.

SECTION 5

Complete Operator Reference

The table below shows every assignment operator you are likely to encounter. The arithmetic operators are the most common, but the exponentiation and remainder operators come up frequently in game development, animations, and math-heavy applications.

OperatorNameExampleEquivalent To
=Simple Assignmentx = 10—
+=Addition Assignmentx += 5x = x + 5
-=Subtraction Assignmentx -= 3x = x - 3
*=Multiplication Assignmentx *= 2x = x * 2
/=Division Assignmentx /= 4x = x / 4
%=Remainder Assignmentx %= 3x = x % 3
**=Exponentiation Assignmentx **= 2x = x ** 2

Arithmetic assignment operators in JavaScript

Tracing x Through Multiple Assignment OperatorsStarting value: let x = 20let x = 2020→x += 525→x *= 250→x -= 842↓x /= 76→x %= 42→x **= 38Trace Summarylet x = 20; // x is 20x += 5; // 20 + 5 = 25x *= 2; // 25 * 2 = 50x -= 8; // 50 - 8 = 42x /= 7; // 42 / 7 = 6x %= 4; // 6 % 4 = 2x **= 3; // 2³ = 8
This diagram traces the variable x through seven compound assignment operations. Each box shows the operation performed and the resulting value. Follow the arrows to see how the value transforms from 20 to a final value of 8.

Walking through this trace is exactly how you should debug compound assignment operators in your own code. If you ever get an unexpected result, add console.log(x) after each line to see the intermediate values, just like the boxes in the diagram above.

SECTION 6

Worked Example — Building a Score Tracker

Imagine you are building a simple game where a player earns and loses points. Let's use assignment operators to track the score through several events.

Game Score Tracker

  1. 1

    Step 1 — Initialize the Score

    Start by declaring a variable to hold the player's score. We use let because the value will change.
    let score = 0; → score is 0
  2. 2

    Step 2 — Player Defeats an Enemy (+50 points)

    The player earns 50 points. Use += to add 50 to the current score.
    score += 50; → 0 + 50 = 50
  3. 3

    Step 3 — Player Finds a Double-Points Power-Up (×2)

    A power-up doubles the current score. Use *= to multiply the score by 2.
    score *= 2; → 50 × 2 = 100
  4. 4

    Step 4 — Player Takes Damage (−25 points)

    The player takes damage and loses 25 points. Use -= to subtract from the score.
    score -= 25; → 100 − 25 = 75
  5. 5

    Step 5 — Points Split Among 3 Team Members

    The 75 points are divided equally among 3 teammates. Use /= to divide.
    score /= 3; → 75 / 3 = 25
  6. 6

    Step 6 — Display the Final Score

    We can verify our result with console.log(score). The final score for each team member is 25 points.
    console.log(score); → Output: 25
💡

Pro Tip

You can chain these operations in sequence because each one updates the variable in place. The order matters — just like in a recipe, doing the steps out of order changes the final result.

SECTION 7

Long Form vs. Shorthand — When to Use Each

You might wonder whether you should always use the shorthand. The answer is almost always yes for simple updates, but there are some situations where the long form is clearer. The table below breaks down the trade-offs.

CriteriaLong Form (x = x + y)Shorthand (x += y)
ReadabilityExplicit — shows every part of the operationConcise — experienced developers prefer this
Error RiskHigher — typing the variable name twice creates typo riskLower — variable name appears only once
PerformanceIdentical in modern enginesIdentical in modern engines
Complex ExpressionsBetter when the left side involves a complex lookupMay evaluate the left side only once (subtle advantage)
Beginner ClarityEasier to understand at firstRequires learning the shorthand pattern

Comparing long-form and compound assignment

✦

KEY TAKEAWAY

In professional JavaScript code, compound assignment operators are the standard. Think of it like texting shorthand — everyone knows what "brb" means, and writing "be right back" every time would slow you down. Once you learn +=, -=, and their siblings, they become second nature and make your code faster to write and read.

SECTION 8

Connection to Advanced Operators

The compound assignment pattern extends beyond basic arithmetic. As you advance in JavaScript, you will encounter bitwise assignment operators and logical assignment operators that follow the exact same x op= y pattern. Understanding the arithmetic versions now gives you a solid foundation for these more advanced tools.

CategoryOperatorsWhen You'll Use Them
Arithmetic (this lesson)+= -= *= /= %= **=Everyday variable updates, counters, accumulators, math calculations
Bitwise&= |= ^= <<= >>= >>>=Low-level programming, color manipulation, flags, permissions systems
Logical (ES2021)&&= ||= ??=Setting default values, conditional assignment, null-safe updates

The assignment operator family in JavaScript

The logical assignment operators deserve a quick preview. The nullish coalescing assignment operator (??=) assigns a value only if the variable is currently null or undefined. For example, username ??= "Guest" sets the username to "Guest" only if it hasn't been set yet. You'll explore these in depth once you learn about truthy and falsy values.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words what the expression count += 1 does. How is it different from count = 1?
Show answer
The expression count += 1 reads the current value of count, adds 1 to it, and stores the result back in count. It is equivalent to count = count + 1. In contrast, count = 1 simply overwrites whatever value was in count with the number 1, regardless of what was there before. The key difference is that += builds on the existing value while = replaces it entirely.

Question 2: BASIC CALCULATION

What is the value of x after these lines run? let x = 12; x -= 4; x *= 3;
Show answer
Start with x = 12. After x -= 4, x becomes 12 − 4 = 8. After x *= 3, x becomes 8 × 3 = 24. The final value of x is 24. Remember that each operation uses the result of the previous one — the order matters.

Question 3: INTERMEDIATE

Predict the output of this code: let a = 100; a /= 5; a %= 7; a **= 2; console.log(a);
Show answer
Let's trace through step by step. Start: a = 100. After a /= 5, a = 100 / 5 = 20. After a %= 7, a = 20 % 7 = 6 (since 7 goes into 20 twice with remainder 6). After a **= 2, a = 6² = 36. The console outputs 36. The remainder operator is the trickiest step — it divides and keeps only the leftover.

Question 4: APPLIED

You are writing a shopping cart program. The variable total starts at 0. A user adds items costing $15.99, $24.50, and $9.99. Then a 10% discount is applied (multiply by 0.9). Write the code using only compound assignment operators and state the final total.
Show answer
The code would be: let total = 0; total += 15.99; total += 24.50; total += 9.99; total *= 0.9; After adding all three items, total = 15.99 + 24.50 + 9.99 = 50.48. After the 10% discount (total *= 0.9), total = 50.48 × 0.9 = 45.432. In a real application, you would round to two decimal places using total = Math.round(total * 100) / 100 to get $45.43.

Question 5: CRITICAL THINKING

Consider this code: let result = "Score: "; result += 100; result += 50; What is the final value of result? Why doesn't += add the numbers together? How would you fix the code if you wanted the sum to appear after "Score: "?
Show answer
The final value is the string "Score: 10050". Because result starts as a string, the += operator performs string concatenation instead of addition. The number 100 is converted to the string "100" and appended, then 50 is converted to "50" and appended. To fix this, you could calculate the sum separately and then concatenate: let total = 100 + 50; let result = "Score: " + total; which gives "Score: 150". This illustrates why understanding type coercion is essential when using +=.

SUMMARY

Lesson Summary

Summary

Assignment operators are tools for storing and updating values in variables. The basic simple assignment operator (=) stores a value, while compound assignment operators like +=, -=, *=, /=, %=, and **= combine an arithmetic operation with assignment in a single step. Every compound operator follows the pattern x op= y which is equivalent to x = x op y.

Key things to remember: JavaScript always evaluates the right side first before performing the assignment. The += operator performs string concatenation when used with strings, which can cause unexpected results if you mix types. These operators reduce repetition, prevent typos, and make your code easier to read — they are the industry standard for updating variables in professional JavaScript.

Varsity Tutors • JavaScript • Assignment Operators — Use assignment operators (+=, -=, etc.)