Explicit Equality
Sometimes knowing if something is equal just isn't enough and we need to know if it is explicitly equal. This is a fantastic continuation from our last video that explained about matching between different data types. In this video we'll look into how explicit equality operators work - '===' and '!==='.
In the above comparisons, the values were said to be equal even if they are close to each other. But there are situations where we need to check for explicit equality. We want the output to be false even if there is minor difference between the two. The two values must be absolutely equal to satisfy the explicit equality condition. This operator uses the === symbol. Let's recap now: one equal sign (=) is an assignment operator, two equal signs (==) is an equality operator and three equal signs (===) is the Explicit Equality Operator.
Equality Operator (==) and Explicit Equality Operator (===)
Whenever we use the symbol ===, we mean that the comparison should be explicit. For example let us consider a Boolean variable isTrue whose value is true and trace the comparison using trace(isTrue==1). We know that the best alternative for true is 1. So the application gives the output as true because the equality operator (==) is used for the comparison. But when we use the explicit equality operator (===), the result is totally different. The compiler now wants both the values inside the trace to be absolutely equal. The fact that 'true is equal to 1' is not enough to satisfy the Explicit Equality condition. The result in this case would be false. But if we have trace(isTrue===true) or trace(1===1), the result would be true for both the cases as the values are explicitly equal.
Inequality Operator (!=) and Explicit Inequality Operator (!==)
The Explicit Inequality Operator works the same as the Inequality Operator but it wants the values to be explicitly unequal, the reverse of the above: we check for inequality rather than equality. Let's see an example to differentiate between (!=) and (!==). If we write trace(isTrue!=1), the result is false because for normal equality isTrue is considered as 1. But if we write trace(isTrue!==1), the result is true because for explicit equality isTrue is not equal to 1. Therefore, this satisfies the explicit inequality condition and hence, we can expect the result as true.
Don't get confused with these four different types of operators. To sum up, you can remember the following points and avoid confusion. == and != checks for equality and inequality respectively but consider the closest value as well during comparison. === and !== checks for explicit equality and explicit inequality respectively and the comparison requires the values to be absolutely equal or absolutely unequal.