You are here: / Articles / Programming / Technology / A Tale of Two Equality Operators (== vs ===) in JavaScript and PHP

A Tale of Two Equality Operators (== vs ===) in JavaScript and PHP

Equality Operators

Share!



Before you run off and write to the JavaScript and PHP maintainers to complain about a type or syntax error or duplication or whatever it is good to note that there is no mistake with the equality operators in these languages.

As a matter of fact the == vs === operators have their place and even go by different names. The Equality operator (==) is definitely different from the identity operator (===). Now if they both behave the same, why do we need two operators to do the same thing? I guess that is why you are here to find out, and we won’t disappoint you.

The two equality operators basically do the same thing but it is the way they do them that differs. The identity operator will not bother to do extra work just to force a positive or true comparison. It is therefore quite “lazy” in that aspect compared to the equality operator. The latter will do some necessary conversions before comparing whatever it needs to.

This brings in a little overhead and therefore from a performance stand point, the identity operator is faster. It is also a safer operator and it compares apples to apples and does not try to force a peach to be an apple.

Read Also  Of Speed, Memory and the Data Set in Computers

With the equality operator 10 and ’10’ and equal because they can be cast into each other successfully. In the strict sense as far as the identity operator goes 10 is not equal to ’10’. In human speak the first one is a number while the second is a word. This makes them have different data types and that is exactly what the identity operator factors in.

Where appropriate the === operator will also do the necessary checks before comparing. For instance var a = 'Hou'+'se'; would be true and be equal to var b = 'House';. In the former the strings will be concatenated before the comparison is made. What is important to note is that in both cases a and b would match in value and datatype.

The sister operators != and !== follow the same basic rules but in this case they look for not equal rather than equals. The != will perform all the necessary type conversions before comparing while the !== operator will just compare the values and the data types.