What Is 'Not Not' Or 'Double Negation' `!!` Operator In Elixir?

Amir Hussain
What Is 'Not Not' Or 'Double Negation' `!!` Operator In Elixir?

The !! operator (double-exclamation mark) in Elixir is called the "not not" operator, or the "double negation" operator. It is a way to "force" a value to be interpreted as a boolean by negating it twice.

In Elixir and many other programming languages, the ! operator is used to negate a boolean value. It returns the opposite of a boolean value: true if the value is false, and false if the value is true.

The !! operator in Elixir is a shorthand way to "force" a value to be interpreted as a boolean. It takes the value on its right-hand side and returns true if the value is "truthy", and false if the value is "falsy".

The !! operator is simply two ! operators used together, which negates a value twice. This has the effect of "forcing" the value to be interpreted as a boolean because any value that is not false or nil will be considered "truthy" and will be negated to false by the first !, and then negated again to true by the second!

In Elixir, a value is considered "truthy" if it is not one of the following: false, nil, or the empty list []. All other values, including numbers, strings, and data structures, are considered "truthy".

Here is an example of how the !! operator might be used:

iex>x = true
 true
iex>!!x
 true
iex>y = "hello"
 "hello"
iex>!!y
 true
iex>z = nil
 nil
iex>!!z
 false

You can use the !! operator to force a value to be interpreted as a boolean in situations where you need to pass a boolean value as an argument to a function or method, or when you need to use a boolean value in a conditional expression.

Keep in mind that the !! operator does not actually change the value of the expression it is applied to. It simply returns a boolean representation of the value.


Let's Talk

Dropping a line to say g'day, ask for my resume or see if we can build something amazing together? I'd love to hear from you!

copyright©2023 AMir Hussain all rights reserved