Assignment operators
- Node.js course
- Beginner
- Lesson 25/116
- 4 min
Learn shortcut assignments with =, +=, -=, *=, /= and ++/--.
Assignment operators
The assignment operator = gives a value to a variable. For example, let x = 5. x now holds 5.
Compound assignment combines operation and assignment: x += 3 is the same as x = x + 3. Similarly there are -=, *=, /=, %=.
This shortens long expressions. Especially when updating a counter, count += 1 is common.
Increment and decrement
The increment and decrement operators are written with ++ and --. They increase or decrease a variable's value by 1.
For example, after let count = 5; count++;, count becomes 6. The same can be done with count += 1; both give the same result.
There is a small difference between ++count (prefix) and count++ (postfix): prefix increments then returns the value, postfix returns the value then increments. The difference does not matter when used alone.
Practice Calculate with compound assignment
Declare let total = 100. Add 20 with total += 20, then subtract 10 with total -= 10, then double with total *= 2. Finally call console.log(total).
Starter code
let total = 100;
// Change total with +=, -= and *=
// Log it with console.log at the endSample solution
let total = 100;
total += 20;
total -= 10;
total *= 2;
console.log(total);Expected output
220
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Compound assignment
let count = 5;
count ____ 2;
let count = 5;
count += 2;
Explanation: += adds the right side to the left.
2 Match the assignment types
| Term | Meaning |
|---|---|
= |
Assignment |
+= |
Add and assign |
-= |
Subtract and assign |
++ |
Increment by one |
3 What does x++ do?
- Adds 1 to x Correct answer
- Adds 2 to x
- Decrements x by one
- Resets x
Explanation: The correct answer: adds 1 to x. The ++ operator increments by 1.