Flow Control

The convention of optional parentheses continues with CoffeeScript’s if and else keywords:

if true == true
  "We're ok"

if true != true then "Panic"

# Equivalent to:
#  (1 > 0) ? "Ok" : "Y2K!"
if 1 > 0 then "Ok" else "Y2K!"

As you can see above, if the if statement is on one line, you’ll need to use the then keyword so CoffeeScript knows when the block begins. Conditional operators (?:) are not supported; instead you should use a single line if/else statement.

CoffeeScript also includes a Ruby idiom of allowing suffixed if statements:

alert "It's cold!" if heat < 5

Instead of using the exclamation mark (!) for negation, you can also use the not keyword—which can sometimes make your code more readable, as exclamation marks can be easy to miss:

if not true then "Panic"

In the example above, we could also use the CoffeeScript’s unless statement, the opposite of if:

unless true
  "Panic"

In a similar fashion to not, CoffeeScript also introduces the is statement, which translates to ===:

if true is 1
  "Type coercion fail!"

As an alternative to is not, you can use isnt:

if true isnt true
  alert "Opposite day!"

You may have noticed in these examples that CoffeeScript is converting == operators into === and != into !==. This is one of my favorite features of the language, and yet one of the most simple. What’s the reasoning behind this? Well, frankly, JavaScript’s type coercion is a bit odd, and its equality operator coerces types in order to compare them, leading to some confusing behaviors and the source of many bugs. There’s a longer discussion on this topic in Chapter 6.

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.