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) returns true (unlike NaN === NaN, which returns false).
  • Object.is(+0, -0) returns false (unlike +0 === -0, which returns true).

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): If x and y are strictly equal, we have to further check if they are both +0 or -0.
    • For +0 and -0, the check x !== 0 || 1 / x === 1 / y ensures they are distinguished by checking the signs via division.
  • NaN Case: NaN is the only JavaScript value that is not equal to itself, so the condition x !== x && y !== y checks if both x and y are NaN.

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()

  1. Comparing Special Cases: Determine if two values are the same, including special cases like NaN and distinguishing between +0 and -0.
  2. Strict Comparisons: When strict equality is not sufficient and corner cases need handling.
  3. Custom Implementations: Understanding the internals of Object.is() helps in situations requiring customized equality checks.