Condition of if

In Elixir, if executes a doend block unless the given condition is false or nil as you know.

iex(1)> if true, do: IO.puts("ok")
ok
:ok
iex(2)> if 3, do: IO.puts("ok")
ok
:ok
iex(3)> if false, do: IO.puts("ok")
nil
iex(4)> if nil, do: IO.puts("ok")
nil
iex(5)> if "ok", do: IO.puts("ok")
ok
:ok

I’d like to know how to check whether the given argument for if is true. The only way I thought out for checking it is below.

if a == true, do: IO.puts("ok")

I feel a == true is somehow weird, are there any better ways to check true?

1 Like

In Elixir, with the exception of guards, the principle is of truthyness meaning that for boolean comparisons, nil and false are considered false and everything else is true.

Meaning if you truly want to check for the atom true you will need to do a == true as you are doing. The values true, false and nil are just atoms in Elixir, nothing more.

5 Likes

Thank you. I will do a == true in Elixir!

1 Like