3.8

Constant

We glossed over an important detail when we were discussing variables. After we have put a constraint on a value of the variable x like this: 3x - 5 = 7, it essentially turns into a constant. Let’s write it another way to make this point clearer: x = (7 + 5) / 3. In this scenario, x can have only one value and that is 4. It can never change. It will remain 4 forever, until the end of time. It looks as if we have discovered a way to give a name to an expression. We can refer to the expression (7 + 5) / 3 as x now. If we see another expression that uses x, we can safely replace it with (7 + 5) / 3. As it turns out, Elm also lets us name expressions like this:

> x = (7 + 5) / 3
4

> x
4

> meaningOfLife = 42
42

> meaningOfLife
42

From now onwards, we will use the term constant for something that gives a name to an expression. Elm also defines constants of its own, for example here is our favorite constant from mathematics:

> pi
3.141592653589793

Naming Constants

Elm provides certain guidelines for naming constants.

Camel Case

The first letter of a constant must be written in lowercase and the first letter of each subsequent concatenated word should be capitalized. This style of naming is called Camel Case.

> meaningOfLife = 42   -- Valid name for a constant
42
> MeaningOfLife = 42   -- Invalid name for a constant

Numbers

A constant can have numbers in its name.

> height1 = 6
6

Although height1 is a valid name in Elm, it’s recommended that you minimize the use of numbers in a name. Numbers are cryptic and they don’t reveal much about the information represented by a constant.

Apostrophes

Prior to the 0.18 version, Elm allowed apostrophes in a constant’s name. Not anymore.

> name' = "Walter"   -- Invalid name for a constant

Underscore

A constant can also have an underscore in its name.

> base_height = 4   -- Valid but not recommended
4

However, as we covered before, Elm style conventions dictate that constant names are written in Camel Case. When there is an underscore in between words, that is called Snake Case.

Just like numbers, we may feel the temptation to add an underscore to the end to create a constant that represents a similar concept we have dealt with before.

> name = "Sansa"
"Sansa"

> name_ = "Stark"  -- Valid but not recommended
"Stark"

I encourage you to replace an underscore with a meaningful word to describe the subtle difference.

> firstName = "Sansa"
"Sansa"

> lastName = "Stark"  -- Much better
"Stark"

Special Characters

A constant cannot have a special character (e.g. $, #, or &) in its name.

> height$ = 7  -- Invalid name for a constant
Back to top
Close