Assignment Operators
What you'll learn: How to update variable values efficiently using assignment and compound assignment operators.
The Basic Assignment Operator
You've already seen the basic assignment operator =, which stores a value in a variable:
x = 5
This puts the value 5 into the variable x.
Compound Assignment Operators: Shortcuts for Updates
Often you'll want to update a variable based on its current value. You could write:
x = x + 3
But programming languages offer compound assignment operators that combine an arithmetic operator with assignment, making your code more concise:
+=adds and assigns:x += 3meansx = x + 3-=subtracts and assigns:x -= 2meansx = x - 2*=multiplies and assigns:x *= 4meansx = x * 4/=divides and assigns:x /= 2meansx = x / 2
Why Use Them?
Think of compound operators like saying "add 3 to x" instead of "set x to the value of x plus 3." It's clearer, faster to type, and exactly matches how you think about the operation. They're especially useful when variable names are long or when updating counters in loops.
Example
score = 100
score += 50 // score is now 150
score -= 20 // score is now 130
score *= 2 // score is now 260
score /= 4 // score is now 65
Each compound operator reads the current value, performs the operation, and stores the result back—all in one efficient step.
Key Takeaway: Compound assignment operators (+=, -=, *=, /=) provide a concise way to update variables by combining arithmetic operations with assignment in a single operator.