JavaScript
This page explains how JavaScript assignment operators store a value in a variable and update the value with a calculation.
Goal: use = to assign a value, then choose a compound assignment operator when updating the current value.
Assignment operators
An assignment puts the value on the right into the variable on the left. The simplest assignment operator is =.
JavaScript
let score = 5;
score = 8; // score is now 8The right-hand expression is evaluated first, then its result is stored in the variable.
Compound assignment operators
Compound operators combine a calculation with an assignment. For example, score += 3 means approximately score = score + 3.
| Operator | Meaning | Example |
|---|---|---|
+= | add and assign | x += 3 |
-= | subtract and assign | x -= 3 |
*= | multiply and assign | x *= 3 |
/= | divide and assign | x /= 3 |
%= | remainder and assign | x %= 3 |
JavaScript
let count = 10;
count += 2; // 12
count -= 3; // 9
count *= 2; // 18
count /= 3; // 6
count %= 4; // 2Things to remember
=assigns a value; it does not test equality. Use===when comparing values.- The variable must be assignable. A
constbinding cannot be assigned a new value, so useletwhen the binding itself will change. - Be careful when combining strings and numbers:
"total: " + 3produces text, while numeric calculations need numeric values.