Assignment operators
As you’ve already seen, you can assign values using the =
operator.To assign only if the assigned-to variable is null,use the ??=
operator.
// Assign value to a
a = value;
// Assign value to b if b is null; otherwise, b stays the same
b ??= value;
Compound assignment operators such as +=
combinean operation with an assignment.
= | –= | /= | %= | >>= | ^= |
+= | *= | ~/= | <<= | &= | |= |
Here’s how compound assignment operators work:
Compound assignment | Equivalent expression | |
---|---|---|
For an operator op: | a op= b | a = a op b |
Example: | a += b | a = a + b |
The following example uses assignment and compound assignmentoperators:
var a = 2; // Assign using =
a *= 3; // Assign and multiply: a = a * 3
assert(a == 6);