# CoffeeScript’s tertiary operation

## Problem

I need to change the value of a variable based on a condition.

What’s the quickest method to accomplish this with CoffeeScript?

For example, here’s how I’d do it in JavaScript:

``````a = true  ? 5 : 10  # => a = 5
a = false ? 5 : 10  # => a = 10
``````

## Solution #1

You can just use if/else because everything is an expression and hence produces a value.

``````a = if true then 5 else 10
a = if false then 5 else 10
``````

More examples of expressions can be found here.

## Solution #2

``````a = if true then 5 else 10
a = if false then 5 else 10
``````

See documentation.

## Solution #3

This should work in practically any language instead:

``````a = true  && 5 || 10
a = false && 5 || 10
``````

## Solution #4

The javascript ternary operator is not supported by Coffeescript. The following is the reason given by the coffeescript author:

Please see https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802 for further information.

## Solution #5

If it’s primarily true use, you can split it into two statements:

``````a = 5
a = 10 if false
``````

If you need more options, you can use a switch statement:

``````a = switch x
when true then 5
when false then 10
``````

It may be oversized with a boolean, but I find it quite readable.