Java Reference
In-Depth Information
Comparison
We often need to compare values when we are programming. JavaScript has several ways to
compare two values.
Equality
Remember earlier, when we assigned a value to a variable? We used the
=
operator to do
this, which would be the logical choice for testing if two values are equal.
Unfortunately, we can't use it because it is used for assigning values to variables. For ex-
ample, say we had a variable called
answer
and we wanted to check if it was equal to
5
,
we might try doing this:
answer = 5;
<< 5
What we've actually done is
assign
the value of 5 to the variable
answer
, effectively over-
writing the previous value!
The correct way to check for equality is to use either a double equals operator,
==
, known
as "soft equality" or the triple equals operator,
===
, known as "hard equality".
Soft Equality
We can check if
answer
is in fact equal to 5 using soft equality, like so:
answer == 5;
<< true
This seems to work fine, but unfortunately there are some slight problems when using soft
equality:
answer == "5";
<< true
