Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 48 ยท Core Language

Operators and Comparison

Learn Elixir's arithmetic, comparison, boolean and string operators, the difference between and and &&, ranges, in, and how any two terms are ordered.

Elixir has the operators you would expect, plus a few that look familiar but behave differently. The classic traps are == versus ===, and versus &&, and the fact that + does not join strings. This lesson walks through them so nothing surprises you later.

All examples below are read-only Elixir unless marked as a JavaScript stand-in. Elixir is not installed on this site, so stand-ins are used where a live demo helps. They imitate the rules and are not real Elixir.

Arithmetic

ELIXIR
1 + 2      # 3
10 - 4     # 6
3 * 4      # 12
10 / 4     # 2.5
10 / 5     # 2.0, the / operator always returns a float
div(10, 4) # 2, integer division
rem(10, 4) # 2, remainder (sign follows the dividend)

The key surprise is /. Even when the result is a whole number, you get a float (2.0). Use div/2 and rem/2 when you want integer results. Integers have arbitrary size, so 2 ** 100 is exact (the ** operator raises a power).

Comparison: == and ===

ELIXIR
1 == 1.0     # true, == compares numeric value
1 === 1.0    # false, === also compares the type (integer vs float)
1 != 1.0     # false
1 !== 1.0    # true
"a" < "b"    # true, strings compare byte by byte

Use == for everyday comparisons. Use === when the difference between 1 and 1.0 matters. Pattern matching is strict, like ===, so 1 = 1.0 raises a MatchError.

Boolean operators: and versus &&

Elixir has two families:

Strict Relaxed Meaning
and && both
or || either
not ! negation

The strict ones expect a boolean (true or false) on the left. The relaxed ones accept any value and treat only nil and false as falsy:

ELIXIR
true and false      # false
false or true       # true
not true            # false

1 and 2             # ** (BadBooleanError) expected a boolean on the left side of "and", got: 1

nil || "default"    # "default"
"hello" && 42       # 42, returns the right side when the left is truthy
nil && 42           # nil
!0                  # false, because 0 is truthy in Elixir

Notice the return values. || returns the first truthy operand, and && returns the left operand when it is falsy, otherwise the right one. Both short-circuit, so the right side is not evaluated when the left already decides the answer. Use and/or when you really have booleans (it catches mistakes early) and &&/|| when you want the "default value" idiom.

Zero, the empty string and the empty list are truthy in Elixir. Only nil and false are falsy. Do not write checks the way you would in JavaScript or Python.

Strings, lists and membership

The + operator is only for numbers. Strings join with <>, lists with ++:

ELIXIR
"Hello, " <> "world"      # "Hello, world"
[1, 2] ++ [3]             # [1, 2, 3]
[1, 2, 3, 2] -- [2]       # [1, 3, 2], removes the first match only
"user: #{1 + 1}"          # interpolation builds strings too
2 in [1, 2, 3]            # true
"hello" =~ "ell"          # true, the left string contains the right one
"hello" =~ "xyz"          # false

<> also works on patterns, which you will use heavily later: "Hi " <> name = "Hi Ana" binds name to "Ana". The left side of <> in a pattern must be a literal string. More on that in Strings and Binaries. Lists are explained in Tuples and Lists.

Ranges

A range is a compact description of a sequence of integers:

ELIXIR
1..5          # 1, 2, 3, 4, 5
1..10//3      # 1, 4, 7, 10 (a step of 3)
5..1//-1      # 5, 4, 3, 2, 1
3 in 1..5     # true
Enum.to_list(1..3)  # [1, 2, 3]

Ranges are lazy: 1..1_000_000 does not build a million-element list. When you count downward, always write the step (5..1//-1) so your intent is clear.

Any two terms can be compared

Elixir lets you compare values of different types, which is handy when sorting mixed data. The rule is a fixed order:

Text
number < atom < reference < function < port < pid < tuple < map < list < bitstring

So 1 < :a is true, :z < {1} is true, and [1] > %{a: 1} is true. Within a type the natural order is used. Tuples are compared by size first, then element by element. Lists compare element by element from the front. Maps compare by size, then keys, then values.

ELIXIR
{1, 2, 3} > {9, 9}    # true, a bigger tuple wins
[1, 2] < [1, 3]       # true
:apple < :banana      # true, atoms compare by name

This ordering is what Enum.sort/1 uses, so you can sort a list that mixes numbers and atoms without an error.

A JavaScript stand-in for term ordering

The stand-in tags each value with a type and applies the ranking above to a small subset of types. It is a model of the rule, nothing more.

JS Elixir term ordering (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The numbers come first, then atoms, then tuples (shorter before longer), then lists, which matches the order in the table.

The next stand-in contrasts the two boolean families and the two equality operators. JavaScript's own rules differ, so we write small functions that follow Elixir's rules.

JS and versus && (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 10 / 5 return in Elixir?

    The / operator always returns a float. Use div(10, 5) for the integer result 2.
  2. 2. What is the result of nil || "default"?

    || accepts any value, treats nil and false as falsy and returns the right operand when the left is falsy.
  3. 3. What happens with 1 and 2?

    and requires a boolean on the left side. Use && when the operands are not strictly booleans.
  4. 4. Which comparison is true?

    == compares numeric value, so it is true. === also compares the type, and the term order is number < atom < tuple < list, so the other two are false.

Summary

  • / always returns a float; use div/2 and rem/2 for integers.
  • == compares values, === also compares integer versus float.
  • and, or and not need booleans on the left; &&, || and ! work with any value, where only nil and false are falsy.
  • Join strings with <> and lists with ++; remove with --.
  • in tests membership, and ranges (1..10//2) are lazy descriptions of integer sequences.
  • Different types can be compared: number < atom < reference < function < port < pid < tuple < map < list < bitstring.

Next up: Tuples and Lists.