Equality Operators
This section describes the JavaScript
equality and inequality operators. These are operators that compare
two values to determine whether they are the same or different and
return a boolean value (true
or
false
) depending on the result of the comparison.
As we’ll see in Chapter 6, they are most
commonly used in things like if
statements and
for
loops, to control the flow of program
execution.
Equality (==) and Identity (===)
The ==
and
===
operators check whether two values are the
same, using two different definitions of sameness. Both operators
accept operands of any type, and both return true
if their operands are the same and false
if they
are different. The ===
operator is known as the
identity operator, and it checks whether its two operands are
“identical” using a strict definition of sameness. The
==
operator is known as the equality operator; it
checks whether its two operands are “equal” using a more
relaxed definition of sameness that allows type conversions.
The identity operator is standardized by ECMAScript v3 and
implemented in JavaScript 1.3 and later. With the introduction of the
identity operator, JavaScript supports =
,
==
, and ===
operators. Be sure
you understand the differences between the assignment, equality, and
identity operators, and be careful to use the right one when coding!
Although it is tempting to call all three operators
“equals,” it may help to reduce confusion if you read
“gets or is assigned” for =
, “is equal to” for ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.