Beginning AngularJS

(WallPaper) #1
ChApter 1 ■ JAvASCrIpt You Need to KNow

Equality vs. Identity

I mentioned previously that I’d like to cover some of these operators as special cases. The identity (===) and equality
(==) operators are one such special case. These operators look similar, and they can even appear to behave similarly,
but, in fact, they are significantly different.
When performing comparisons, the equality operator (==) will attempt to make the data types the same before
proceeding. On the other hand, the identity operator (===) requires both data types to be the same, as a prerequisite.
This is one of those concepts best conveyed through code, as shown in Listing 1-14.


Listing 1-14. Converting Types and Then Comparing


<!DOCTYPE html>




JavaScript Primer





I’m not sure what you expect to see in the output that follows, given that we are comparing the number 3 to the
string value "3". You may or may not be surprised, but these values are considered to be the same.


ValueOne and ValueTwo are the same


The reason why the == operator reasons that "3" and 3 are the same is because it actually coverts the operands
(the values either side of the == operator) to the same type before it does the comparison. However, if we change the
operator to an identity operator, as shown here, we see quite different output:


if (valueOne === valueTwo)


ValueOne and ValueTwo are NOT the same


Since we used the === operator on this occasion, and because this operator does not do any type conversion, we
see that the string value "3" and the number 3 are not the same after all.
When in doubt, a relatively safe choice is simply to use the identity operator (===) as a matter of habit. Of course,
the safest choice is to familiarize yourself with the differences, so that you know what is actually happening under the
hood.

Free download pdf