Implementing a Custom Object.is() Method in JavaScript
The Object.is()
method in JavaScript determines whether two values are the same. It is similar to the ===
operator but has some differences, such as treating NaN
as equal to NaN
and distinguishing between +0
and -0
.
Let's implement a custom version of Object.is()
and understand its behavior.
Understanding Object.is()
Object.is()
is used to determine if two values are the same. It behaves similarly to the strict equality (===
) operator but with a few key differences:
Object.is(NaN, NaN)
returnstrue
(unlikeNaN === NaN
, which returnsfalse
).Object.is(+0, -0)
returnsfalse
(unlike+0 === -0
, which returnstrue
).
Real Interview Insights
Interviewers might ask you to:
- Implement a function that mimics the behavior of
Object.is()
. - Handle edge cases such as
NaN
,+0
, and-0
.
Implementing customObjectIs
Function
Here’s how you can implement a custom Object.is()
function:
function customObjectIs(x, y) {
if (x === y) {
// +0 and -0 case
return x !== 0 || 1 / x === 1 / y;
}
// NaN case
return x !== x && y !== y;
}
Explanation:
- Strict Equality Check (
x === y
): Ifx
andy
are strictly equal, we have to further check if they are both+0
or-0
.- For
+0
and-0
, the checkx !== 0 || 1 / x === 1 / y
ensures they are distinguished by checking the signs via division.
- For
- NaN Case:
NaN
is the only JavaScript value that is not equal to itself, so the conditionx !== x && y !== y
checks if bothx
andy
areNaN
.
Practical Examples
Let's see the customObjectIs
function in action:
console.log(customObjectIs(25, 25)); // true
console.log(customObjectIs('foo', 'foo')); // true
console.log(customObjectIs(null, null)); // true
console.log(customObjectIs(undefined, undefined)); // true
console.log(customObjectIs(NaN, NaN)); // true
console.log(customObjectIs(+0, -0)); // false
console.log(customObjectIs(-0, -0)); // true
console.log(customObjectIs(0, 0)); // true
console.log(customObjectIs({}, {})); // false (different objects)
Use Cases for Object.is()
- Comparing Special Cases: Determine if two values are the same, including special cases like
NaN
and distinguishing between+0
and-0
. - Strict Comparisons: When strict equality is not sufficient and corner cases need handling.
- Custom Implementations: Understanding the internals of
Object.is()
helps in situations requiring customized equality checks.