🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Comparison Operators

Comparison operators compare two values and return true or false. Elixir has a loose form and a strict form for checking equality.

Equal and not equal

The == operator answers true or false. The != operator gives the opposite answer.

IO.puts(5 == 5)
IO.puts(5 == 6)
IO.puts(5 != 6)

Loose versus strict equality

Loose equality treats 1 and 1.0 as equal. Strict equality keeps the integer and the float apart.

IO.puts(1 == 1.0)
IO.puts(1 === 1.0)
IO.puts(1 !== 1.0)

Order comparisons

The order operators compare sizes. Strings compare in alphabetical order.

IO.puts(3 < 5)
IO.puts(5 <= 5)
IO.puts(7 > 9)
IO.puts(7 >= 7)
IO.puts("apple" < "banana")

Example

score = 82
passing = 60
IO.puts(score > passing)
IO.puts(score == 100)
IO.puts(score >= 80)
IO.puts(score < 50)

Key points

  • Equality: == checks whether two values are equal.
  • Strict equality: === also requires the two values to have the same type.
  • Difference: != means not equal, and !== means not strictly equal.
  • Order: < means less than, and > means greater than.
  • Inclusive order: <= means less than or equal, and >= means greater than or equal.
  • Text order: strings compare in alphabetical order.

In this example, the score 82 is greater than the passing mark 60, so the first line prints true. The score is not equal to 100, it is at least 80, and it is not less than 50.

Note

comparing 1 and 1.0 shows the loose and strict difference most clearly.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the result of 1 === 1.0?