Assignment Operators
Assignment operators are used to assign values to variables and combine assignment with arithmetic or logical operations.
Simple Assignment
The basic assignment operator (=) assigns a value to a variable.
Usage
let x = 10 |
let name = "mq" |
let items = [1, 2, 3]
Update Operator (|=)
The update operator (|=) applies an expression to a selected value and updates it in place.
Usage
<selector.value> |= expr
The left side specifies what to update using a selector, and the right side is the expression that transforms the value.
Examples
# Change the language of all code blocks to rust
.code.lang |= "rust"
# Update a heading level
.h.depth |= 2
Compound Assignment Operators
Compound assignment operators combine an arithmetic or logical operation with assignment, providing a shorthand for updating variables.
Addition Assignment (+=)
Adds a value to a variable and assigns the result back to the variable.
var x = 10
| x += 5
| x
# => 15
var count = 0
| count += 1
| count
# => 1
Subtraction Assignment (-=)
Subtracts a value from a variable and assigns the result back to the variable.
var x = 10
| x -= 3
| x
# => 7
var balance = 100
| balance -= 25
| balance
# => 75
Multiplication Assignment (*=)
Multiplies a variable by a value and assigns the result back to the variable.
var x = 5
| x *= 3
| x
# => 15
var price = 100
| price *= 1.5
| price
# => 150
Division Assignment (/=)
Divides a variable by a value and assigns the result back to the variable.
var x = 20
| x /= 4
| x
# => 5
var total = 100
| total /= 2
| total
# => 50
Modulo Assignment (%=)
Computes the remainder of dividing a variable by a value and assigns the result back to the variable.
var x = 17
| x %= 5
| x
# => 2
var count = 23
| count %= 10
| count
# => 3
Floor Division Assignment (//=)
Divides a variable by a value, floors the result (rounds down to the nearest integer), and assigns it back to the variable.
var x = 17
| x //= 5
| x
# => 3
var count = 23
| count //= 10
| count
# => 2