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.

  1. // Assign value to a
  2. a = value;
  3. // Assign value to b if b is null; otherwise, b stays the same
  4. b ??= value;

Compound assignment operators such as += combinean operation with an assignment.

=–=/=%=>>=^=
+=*=~/=<<=&=|=

Here’s how compound assignment operators work:

Compound assignmentEquivalent expression
For an operator op:a op= ba = a op b
Example:a += ba = a + b

The following example uses assignment and compound assignmentoperators:

  1. var a = 2; // Assign using =
  2. a *= 3; // Assign and multiply: a = a * 3
  3. assert(a == 6);