I was reading a book on Elixir: Introducing Elixir.
On string compare it says that:
Elixir offers two options for comparing string equality,
==
and===
operators. The==
operator is generally the simplest though the other produces the same result.
Whats the purpose of having two operators if they mean the same thing?
Double Equals ( == ) checks for value equality only. It inherently does type coercion. This means that before checking the values, it converts the types of the variables to match each other. On the other hand, Triple Equals ( === ) does not perform type coercion.
The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false.
JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()
In light of this, most JavaScript experts recommend always using the triple-equals operator, and never using double-equals. The triple-equals operator, as you've probably figured out by now, never does type coercion. So whenever you use triple-equals, you're doing an exact comparison of the actual values.
One example that comes to mind is floats - which use the same comparison functions as strings:
iex> 1 == 1 #true iex> 1 == 1.0 #true iex> 1 === 1 #true iex> 1 === 1.0 #false
And for !==
iex> 1 != 2 #true iex> 1 != 1.0 #false iex> 1 !== 2 #true iex> 1 !== 1.0 #true
It is worth noting that these functions use the following Erlang expressions:
Elixir | Erlang == | == === | =:= != | /= !== | =/=
From the Erlang documentation:
When comparing an integer to a float, the term with the lesser precision is converted into the type of the other term, unless the operator is one of =:= or =/=. A float is more precise than an integer until all significant figures of the float are to the left of the decimal point. This happens when the float is larger/smaller than +/-9007199254740992.0. The conversion strategy is changed depending on the size of the float because otherwise comparison of large floats and integers would lose their transitivity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With