27. Assignment Operators
Assignment operators are used to assign values to variables.
Simple Assignment (=)
javascript let total = 100; // Assigns 100 to total
Compound Assignment Operators (Shorthand)
These operators perform an arithmetic operation and an assignment simultaneously. They are clean and efficient.
| Operator | Shorthand | Equivalent to |
|---|---|---|
+= | 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 |
Example Usage
javascript let balance = 500;
balance += 20; // balance = 500 + 20 => 520 balance *= 2; // balance = 520 * 2 => 1040
console.log(balance); // Output: 1040
Increment and Decrement
++(Increment by 1)--(Decrement by 1)
javascript let counter = 0; counter++; // counter is now 1 counter--; // counter is now 0
Note: Be careful with prefix (++counter) vs. postfix (counter++), as they affect when the variable is updated relative to the expression.