If-Else & Loops
RES@val external isMorning: bool = "isMorning"
@val external showMenu: bool = "showMenu"
@val external displayMenu: unit => unit = "displayMenu"
@val external startValueInclusive: int = "startValueInclusive"
@val external endValueInclusive: int = "endValueInclusive"
@val external testCondition: bool = "testCondition"
ReScript supports if, else, ternary expressions (a ? b : c), numeric for loops, for of, and while. Use break to exit a loop early and continue to skip to its next iteration.
The switch pattern supports a default case. Read more about pattern-matching & destructuring.
If-Else & Ternary
ReScript's if is an expression; it evaluates to its body's content:
Note: an if-else expression without the final else branch implicitly gives () (aka the unit type). So this:
is basically the same as:
Here's another way to look at it. This is clearly wrong:
RESlet result = if showMenu {
1 + 2
}
It'll give a type error, saying basically that the implicit else branch has the type unit while the if branch has type int. Intuitively, this makes sense: what would result's value be, if showMenu was false?
We also have ternary sugar, but we encourage you to prefer if-else when possible.
if-else and ternary are often replaced by pattern matching, which handles a wide range of conditional logic more expressively.
For Loops
Numeric for loops iterate over integers from a starting value up to (and including) the ending value. The loop variable is local to the loop body.
You can make the for loop count in the opposite direction by using downto.
For Of Loops
Use for of to visit each value in an array or an iterable<'a>, without managing an index:
The loop binding must be a variable name or _. To destructure a value, do so inside the loop body:
For asynchronous iteration, see For Await Of.
Break & Continue
break exits the nearest enclosing loop immediately. continue skips the rest of the current iteration and starts the next one. Both work in numeric for, for of, for await of, and while loops.
In a numeric for loop, continue still advances the loop variable. In a while loop, it rechecks the condition, so make sure any necessary updates happen before continue.
You can also use break and continue inside a switch within a loop: they target the loop, not the switch. They cannot be used outside a loop or from a nested function to control an outer loop.
break and continue are reserved keywords, so they cannot be used as ordinary variable names.
While Loops
While loops execute their body while the condition is true. The condition is checked before each iteration, so the body may never run.
Exiting Early
Use break when the stopping condition is discovered inside the loop. There is no need for a separate mutable stop flag: