Assignment operators are used to assign values to JavaScript variables. While the equals
sign = is the most common, JavaScript also provides several compound
assignment operators that act as shortcuts for common operations.
The simple assignment operator = assigns the value of the right-hand operand
to the variable on the left.
let x = 10;
let message = "Hello JavaScript";
= does not mean
"is equal to". It means "take the value on the right and put it into the variable on the
left". To check if two things are equal, we use == or ===.
Compound assignment operators combine an arithmetic operation with an assignment. They are shorthand ways to update the value of a variable based on its existing value.
| Operator | Example | Same As |
|---|---|---|
= |
x = y |
x = y |
+= |
x += y |
x = x + y |
-= |
x -= y |
x = x - y |
*= |
x *= y |
x = x * y |
/= |
x /= y |
x = x / y |
%= |
x %= y |
x = x % y |
**= |
x **= y |
x = x ** y |
The += operator adds a value to a variable and then assigns the result back
to that variable.
let score = 10;
score += 5; // score is now 15
The -= operator subtracts a value from a variable and then assigns the result
back.
let stock = 20;
stock -= 8; // stock is now 12
The *= operator multiplies a variable by a value and then assigns the result
back.
let price = 50;
price *= 2; // price is now 100
The /= operator divides a variable by a value and then assigns the result
back.
let cake = 8;
cake /= 2; // cake is now 4
The += operator can also be used to concatenate (join) strings.
let text = "Learn ";
text += "JavaScript"; // text is now "Learn JavaScript"
= operator is for assignment, not comparison+=, -=, etc.) update a variable based on its current value+= operator works for both numbers and strings