DRAFTThis page is not published. Only visible in development mode.

Conditionals

if branches a script on a condition. It is both a statement - run these statements only when the condition holds - and an expression that produces a value you can bind with let. Together with variables, it turns a request from a fixed pipeline into logic that reacts to data.

if is an expression

Used on the right-hand side of a let, each branch's block produces the value of the whole expression. Run the snippets on this page in order:

$ if as an Expression
$ ctrl+enter to run

Chain any number of conditions with else if; the first one that holds wins:

$ Chain Conditions with else if
$ ctrl+enter to run

No else means maybe none

An if expression without an else has no value to produce when the condition fails, so it produces none. That is often exactly right - "a warning, or nothing" - but if a definite value is required downstream, write the else:

$ No else, No Match: the Result Is none
$ ctrl+enter to run

Guarding writes

As a statement, if runs a block of statements - including inserts, updates, and deletes - only when the condition holds. The whole request is still one transaction, whichever branches run. Note the ; after the closing brace: a block is a statement, and the next statement needs the separator:

$ Guard a Write with if
$ ctrl+enter to run

Branches choose the result

When the if statement is the last thing in a request, the branch that ran determines the request's result - the branches do not have to produce the same shape:

$ Branches Can Produce Different Results
$ ctrl+enter to run

Reassigning outer variables

A branch can assign to a variable declared outside it, which is the imperative alternative to the expression form - useful when several statements in the branch contribute to the final value:

$ Reassign an Outer Variable from a Branch
$ ctrl+enter to run
Many arms? Use match
A long else if chain that compares the same value against many candidates reads better as a match expression - one scrutinee, one arm per case, and an else arm for the rest. See the control flow overview for how the constructs fit together.