Rehan Sattar
Rehan Sattar

Rehan Sattar

Understanding Object.is()

Understanding Object.is()

A quick guide to understanding `Object.is()`

Rehan Sattar
ยทJul 4, 2021ยท

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

The Object.is() method determines whether two values are the same or not. It returns true if the values are the same and false if not.

let's take a look at the syntax.

Object.is(firstValue, secondValue);

๐Ÿ‘‰ Here are some of the major points you have to remember while using Object.is()

  1. Object.is doesn't coerce the values as == do.
  2. It performs === on all the compared values except signed zeroes (+0 and -0) and NaNs.
  3. The === operator (and the == operator) treats the number values -0 and +0 as equal, but Object.is() consider them unequal.
  4. The === operator treats Number.NaN and NaN as not equal but Object.is consider them equal.
  5. If objects/arrays are compared then it will compare both values and the reference in memory
  6. This method is not supported by Internet Explorer yet.

Examples:

// === comparison
Object.is(25, 25);                // true
Object.is('foo', 'foo');          // true
Object.is('foo', 'bar');          // false
Object.is(null, null);            // true
Object.is(undefined, undefined);  // true
Object.is(window, window);        // true
Object.is([], []);                // false

// Object comparison
const foo = { a: 1 };
const bar = { a: 1 };
Object.is(foo, foo);              // true
Object.is(foo, bar);              // false

// Case 2: Signed zero
Object.is(0, -0);                 // false
Object.is(+0, -0);                // false
Object.is(-0, -0);                // true
Object.is(0n, -0n);               // true

// Case 3: NaN
Object.is(NaN, 0/0);              // true
Object.is(NaN, Number.NaN)        // true

That's it, folks! hope it was a good read for you. Thank you! โœจ

๐Ÿ‘‰ References:

The official documentation of Object.is()

๐Ÿ‘‰ Follow me: Github Twitter LinkedIn Youtube

Did you find this article valuable?

Support Rehan Sattar by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this