Elixir Short Circuit Operators — Tentamen Software Testing Blog

Karlo Smid
2 min readJul 21, 2020

--

TL;DR

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, || and &&. We use them to chain several functions that return a boolean value.

False and True

In Elixir, only nil and false are 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 false

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 true

You would use and short circuit operator if the user has to satisfy several conditions to log in:

same_ip && authenticated? && is_admin?

Remember

  • || returns the first expression from the left that is not false
  • && returns the last expression only if all previous expressions are true
  • when to use those short circuit operators

Originally published at https://blog.tentamen.eu on July 21, 2020.

--

--

Karlo Smid
Karlo Smid

Written by Karlo Smid

Founder of Tentamen, software testing agency.

No responses yet