Flow control
Move along in a continuous stream of decisions that should be made.
Fallback
Default or nullish coalescing operations, are defined with double question marks ??
and work the following way:
<maybeNullOrFailedExpression> ?? <fallbackValue>
In case the left-hand side is not null
nor Error
, then it's used; otherwise, the fallback value is returned.
If
If
statements are defined with a question mark ?
, like so:
<condition> ? <response>
as there is no alternative
null
is returned if condition is not met
If-Else
If-Else
statements are defined with a question mark ?
followed by a colon :
, like so:
<condition> ? <response> : <alternativeResponse>
To use multiline If-Else
statements, wrap the response in curly brackets {...}
like so:
<condition> ? {
<response>
} : {
<alternativeResponse>
}
Cases
Cases are defined with the thick arrow =>
and are automatically chained, creating an intuitive and streamlined syntax similar to a switch statement without the possibility of fall-through. This allows for unrelated conditions to be mixed together, ultimately resulting in a more concise if-else-if-else structure:
<condition1> => <responseFor1>
<condition2> => <responseFor2>
<condition3> => <responseFor3>
...
Example:
choose = (x) -> {
x == 1 => 'a'
x == 2 => 'b'
x == 3 => 'c'
}
choose(2) # 'b'
choose(8) # null
To provide a default value for your method, you can add a catch-all case using an underscore _
at the end of the sequence:
choose = (x) -> {
x == 1 => 'a'
x == 2 => 'b'
x == 3 => 'c'
_ => 'd'
}
choose(2) # 'b'
choose(8) # 'd'
For more complex scenarios, you can use blocks as outcomes for each case:
...
condition => {
# do something
'foo'
}
_ => {
# do something else
'bar'
}
...
Cases must end in a catch-all case _
or end of block. The most effective use of Cases is within methods at the bottom of the method body.
While it's possible to add nested Cases, it's best to avoid overly complex constructions. This makes code harder to follow and likely misses the point of using this feature.
It may be more appropriate to extract that logic into a separate method. FatScript encourages developers to split logic into distinct methods, helping to prevent spaghetti code.