This guide delves into the intricacies of JavaScript's strict equality operator (===
), as defined within the ECMAScript specification's "Strict Equality Comparison" section. Let's explore its functionality step-by-step:
===
Algorithm: A Detailed LookThe ===
operator employs the following algorithm to determine equality:
Type Check: The operator first compares the types of the two values. If the types differ, it immediately returns false
. Type matching proceeds to the next step only if types are identical.
Type-Specific Comparison:
Numbers:
NaN === NaN
evaluates to false
(a crucial point of divergence).true
. 0
and -0
are considered equal (true
).Strings: Character-by-character comparison determines equality. Identical sequences yield true
; otherwise, false
.
Booleans: true === true
and false === false
both return true
. Otherwise, false
.
Objects (Arrays and Functions Included): ===
checks for reference equality. Only if both values point to the same memory location (the same object) will it return true
.
null
and undefined
: null === null
and undefined === undefined
return true
. However, null === undefined
is false
due to type differences.
NaN === NaN
is false
This is a frequent source of confusion. The specification defines NaN
(Not-a-Number) as unequal to itself. This is because NaN
represents an invalid or undefined numerical result; comparing two undefined results as equal lacks logical coherence.
Example:
NaN === NaN; // false
To reliably check for NaN
, utilize Number.isNaN()
or Object.is()
:
Number.isNaN(NaN); // true Object.is(NaN, NaN); // true
0 === -0
is true
The specification treats 0
and -0
as equivalent because, in most mathematical operations, their behavior is indistinguishable. However, subtle differences exist in specific scenarios (e.g., 1 / 0
yields Infinity
, while 1 / -0
results in -Infinity
). For situations requiring differentiation, use Object.is()
:
NaN === NaN; // false
When comparing objects, ===
assesses reference equality. Two objects with identical contents are not considered equal unless they are the same object in memory:
Number.isNaN(NaN); // true Object.is(NaN, NaN); // true
But:
Object.is(+0, -0); // false
Further Exploration of JavaScript Fundamentals
The above is the detailed content of Unraveling the '===' of javascript. For more information, please follow other related articles on the PHP Chinese website!