In the section Booleans, we learned about the comparison operators
!=, which test whether two values are equal or not equal, respectively. However, there are some quirks with using the
== operator, which occur when we use
== to compare different data types.
1 2 3
console.log(7 == "7"); console.log(0 == false); console.log(0 == '');
true true true
In order to properly make a comparison, the two operands must be the same type. If the two operands to
== operator is often said to measure loose equality.
Type conversions with
== are carried out according to a complex set of rules, and while many of these conversions make some sense, others do not.
7, so it makes some sense that
7 == "7" returns
true. However, the following example leaves us scratching our heads.
1 2 3
console.log('0' == 0); console.log(0 == ''); console.log('0' == '');
true true false
== operator is non-transitive. We think of equality as being transitive; for example, if A and B are equal and B and C are equal, then A and C are also equal. However, the example above demonstrates that that is not the case for the
== does not follow rules that we typically associate with equality, unexpected results may occur if
=== compares two operands without converting their data types. In other words, if
b are of different data types (say,
a is a string and
b is a number) then
a === b will always be false.
1 2 3
console.log(7 === "7"); console.log(0 === false); console.log(0 === '');
false false false
For this reason, the
=== operator is often said to measure strict equality.
Just as equality operator
== has the inequality operator
!=, there is also a strict inequality operator,
!==. The boolean expression
a !== b returns
true when the two operands are of different types, or if they are of the same type and have different values.
!== WHENEVER POSSIBLE. In this book we will use these strict operators over the loose operators from now on.
What is the result of the following boolean expression?
4 == "4"
What is the difference between
===throws an error if its arguments are of different types.
==converts values of different types to be the same type, while
==works with all data types, while