The behavior of the strict equality operator (===
) is defined in the ECMAScript specification under the section Strict Equality Comparison. Here’s a breakdown of how it works, step by step:
The Algorithm for ===
When you use ===
, JavaScript follows this algorithm to determine if two values are equal:
- Check if the types are the same:
- If the types of the two values are different, return
false
. - If the types are the same, proceed to the next step.
- Compare the values based on their type:
-
Numbers:
- If both values are
NaN
, returnfalse
(yes,NaN === NaN
isfalse
!). - If the numbers have the same numeric value, return
true
. - If one value is
+0
and the other is-0
, returntrue
(they are considered equal).
- If both values are
-
Strings:
- If both strings have the same sequence of characters, return
true
. - Otherwise, return
false
.
- If both strings have the same sequence of characters, return
-
Booleans:
- If both values are
true
or both arefalse
, returntrue
. - Otherwise, return
false
.
- If both values are
-
Objects (including arrays and functions):
- If both values reference the same object in memory, return
true
. - Otherwise, return
false
.
- If both values reference the same object in memory, return
-
null
andundefined
:-
null === null
istrue
. -
undefined === undefined
istrue
. -
null === undefined
isfalse
(they are different types).
-
Why NaN === NaN
is false
This is a common point of confusion. According to the spec, NaN
(Not-a-Number) is defined as not equal to itself. This is because NaN
represents an invalid or undefined numeric result, and it doesn’t make sense to compare two invalid results as equal.
For example:
NaN === NaN; // false
If you need to check if a value is NaN
, use Number.isNaN()
or Object.is()
:
Number.isNaN(NaN); // true
Object.is(NaN, NaN); // true
Why +0 === -0
is true
The spec treats +0
and -0
as equal because, in most cases, they behave the same way in mathematical operations. However, there are rare scenarios where they differ (e.g., 1 / +0
is Infinity
, while 1 / -0
is -Infinity
). If you need to distinguish between them, use Object.is()
:
Object.is(+0, -0); // false
Objects and Reference Equality
When comparing objects (including arrays and functions), ===
checks if they reference the same object in memory. This is why two objects with identical contents are not considered equal:
const obj1 = { name: "Alice" };
const obj2 = { name: "Alice" };
obj1 === obj2; // false (different objects)
But if two variables point to the same object, they are equal:
const obj3 = obj1;
obj1 === obj3; // true (same object)
Top comments (0)