Elixir Short Circuit Operators — Tentamen Software Testing Blog
In the previous post, we explained Elixir Atoms. Today we discuss Elixir short circuit operators and how those could help you to write less code. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Short Circuit Operators
Short Circuit Operators in Elixir are boolean operators. They operate on boolean values, and the result is also boolean value.
We have two Short Circuit Operators,
&&. We use them to chain several functions that return a boolean value.
False and True
In Elixir, only
false, while all other values are
true. In the image above, you can see that in practice.
or short circuit operator returns the first expression from the left that is not
You would use
|| short circuit operator in your application for function chaining:
email_login || facebook_login || google_login
In this example, your application provides three ways to log in, using registered email/password credentials, Facebook, or Google login. Let users in for any of those authentication providers.
and short circuit operator returns the last expression only if all expressions from left to right are
You would use
and short circuit operator if the user has to satisfy several conditions to log in:
same_ip && authenticated? && is_admin?
||returns the first expression from the left that is not
&&returns the last expression only if all previous expressions are
- when to use those short circuit operators
Originally published at https://blog.tentamen.eu on July 21, 2020.