An assignment replaces the value stored in a mutable variable:
score = 10;
The single equals sign means “store the value on the right in the variable on the left.” It differs from the equality operator:
| Code | Meaning |
|---|---|
score = 10; | Change score to 10 |
score == 10 | Produce true when score equals 10 |
Use the previous value
The right side is evaluated before the new value is stored:
score = score + 5;
If score held 10, it now holds 15.
Sugar provides assignment shortcuts for common number changes:
| Shortcut | Equivalent assignment |
|---|---|
score += 5; | score = score + 5; |
health -= 10; | health = health - 10; |
reward *= 2; | reward = reward * 2; |
total /= 4; | total = total / 4; |
wins++; | wins = wins + 1; |
lives--; | lives = lives - 1; |
Read the changed value
Later statements see the new value:
var score = 10;
text {
score += 5;
"Your score is now {score}."
}
The message says Your score is now 15.
Which names may be assigned?
var and let declare mutable variables, so both may be assigned while they are in scope. A const is calculated and read-only, so assigning one is an error.
The assignment above lasts until the current use finishes. On the next use, a regular var starts from its initial value again. A later lesson adds mem when a variable must remember its changed value.
The next lesson uses assignments inside if and else branches.