if/else expressions

if cond1 { ... } [else if condn { ... } ...] [else { ... }]

Curly braces are always required.

The else if and the else sections are optional.

No parentheses are necessary around test conditions.

An if expression can be used inline to create a value.

An if expression always returns a value, even if it's nothing (null).

See also the very expressive and useful given expression.

shortened form if expressions

The shortened form uses parentheses, colons, and semicolons, and no extra keywords.

The shortened form expects a single expression per section rather than a block. The else if and the else sections are optional.

if test1 { 1 } else if test2 { 2 } else { 3 } # long form if expression if(test1: 1; test2: 2; 3) # shortened form if expression

This is a symantic convenience and the result is the same as the long form.


"Truthiness" determines whether a logical test passes or fails. This includes the result of if expressions, logical operators, and alternate tests in given expressions.

The result of this "truthiness" may differ from the result of the toBool() and toBoolOrNull() functions, which serve a different purpose.

value logical result
true truthy
false not truthy
null not truthy
NaN not truthy
empty array not truthy
empty hash not truthy
other truthy

Below is an example of using truthiness to test if a regex pattern matched anything and then using the results. (The matches() function returns an array of progressive matches, and an empty one if there are none.)

val .results = matches re/abc+/, .checkString if .results { ... }