Skip to main content

Compound assignment arithmetic operators

Sometimes we want to do an arithmetic operation in a variable and update its value. For this, we can use compound assignment operators, they perform the operation specified by the operator, then assigns the result to the left variable. Dart supports the following compound assignment arithmetic operators:

NameOperator
Addition+=
Subtraction-=
Multiplication*=
Division/=
Division with integer result~/=
Modulus%=

Let's say we have the following fragment of code:

int myNumber = 5;
myNumber = myNumber + 5;
print(myNumber);

If we replace the + operation with += the code will be:

int myNumber = 5;
myNumber += 5;
print(myNumber);

Writing myNumber = myNumber + 5 is the same as myNumber += 5;. Generally, the advantage of using compound assignment arithmetic operators is a shorter syntax.