Assignment operators

We already encountered the most common assignment operator in mutability, which is the := operator. There are many assignment operators in Motoko. Lets just focus on some essential ones here:

  • := assignment (in place update)
  • += in place add
  • -= in place subtract
  • *= in place multiply
  • /= in place divide
  • %= in place modulo
  • **= in place exponentiation

Lets use all of them in an example:

var number : Int = 5;

number += 2;

number
var number : Int = 5;

number -= 10;

number
var number : Int = 5;

number *= 2;

number
var number : Int = 6;

number /= 2;

number
var number : Int = 5;

number %= 5;

number
var number : Int = 5;

number **= 2;

number

We started by declaring a mutable variable named number, we annotated its name with the type Int and set its value equal to 5. Then we mutate the variable multiple times using assignment operators.