The most basic instance of an if
construct evaluates a condition and executes some code according to the condition outcome. If the condition returns true
, the code within the conditional is executed.
counter = 10
if counter is 10
console.log 'This will be executed!'
The if
construct can be enriched with an else
statement. The code within the else
statement will be executed whenever the if
condition is not met.
counter = 9
if counter is 10
console.log 'This will not be executed...'
else
console.log '... but this one will!'
if
constructs can be chained using else
, without any limitation on how many can be chained. The first conditional that returns true
will run its code and stop the check: no conditional below that point will be evaluated thereafter, and no code block from withing those conditionals will be executed.
if counter is 10
console.log 'I counted to 10'
else if counter is 9
console.log 'I counted to 9'
else if counter < 7
console.log 'Not to 7 yet'
else
console.log 'I lost count'
The opposite form of if
is unless
. Unlike if
, unless
will only run if the conditional returns false
.
counter = 10
unless counter is 10
console.log 'This will not be executed!
The if
statements can be placed in a single line, but in this case, the then
keyword is required.
if counter is 10 then console.log 'Counter is 10'
An alternative syntax is the Ruby-like:
console.log 'Counter is 10' if counter is 10
The last two blocks of code are equivalent.
The ternary operator is a compression of an if / then / else
construct, and can be used when assigning values to variables. The final value assigned to the variable will be the one defined after the then
when the if
condition is met. Otherwise, the value after the else
will be assigned.
outcome = if counter is 10 then 'Done counting!' else 'Still counting'