You are currently looking at the v11.0 docs, which are still a work in progress. If you miss anything, you may find it in the older v10.0 docs here.
If-Else & Loops
ReScript supports if
, else
, ternary expression (a ? b : c
), for
and while
.
ReScript also supports our famous pattern matching, which will be covered in its own section
If-Else & Ternary
Unlike its JavaScript counterpart, ReScript's if
is an expression; they evaluate to their 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 much less used in ReScript than in other languages; Pattern-matching kills a whole category of code that previously required conditionals.
For Loops
For loops iterate from a starting value up to (and including) the ending value.
You can make the for
loop count in the opposite direction by using downto
.
While Loops
While loops execute its body code block while its condition is true.
Tips & Tricks
There's no loop-breaking break
keyword (nor early return
from functions, for that matter) in ReScript. However, we can break out of a while loop easily through using a mutable binding.