Skip to main content

if

The if statement is used to execute a block of code if a condition is truthy.

let x = 5
if x > 3 {
Transmission { "x is greater than 3" }
}
// Outputs "x is greater than 3"

An else clause can be added to execute a block of code if it fails to match all other conditions.

let x = 5
if x > 3 {
Transmission { "x is greater than 3" }
} else {
Transmission { "x is less than or equal to 3" }
}
// Outputs "x is greater than 3"

else if blocks can be added to test multiple conditions.

let x = 7
if x > 10 {
Transmission { "x is greater than 10" }
} else if x > 5 {
Transmission { "x is greater than 5" }
} else {
Transmission { "x is less than or equal to 5" }
}
// Outputs "x is greater than 5"

Returning Values

When if is used in an expression, the last value of each block is returned as the value of the expression.

let x = 7
let a =
if x < 10 {
let prefix = "less than"
prefix + " 10"
} else {
"10 or more"
}
// `a` is "less than 10"

If there is no else block, the resulting value will be undefined.

let x = 99
let a = if x < 10 { "less than 10" }
// a is `undefined`

Returning Multiple Values

To return multiple values from an if expression, separate them using commas:

let x = 7
let a, b =
if x < 10 {
"less than 10", -10
} else {
"10 or less", 10
}
// a is "less than 10", b is -10