Comparing values using Object.is() in Javascript

js

In Javascript, using Object.is() you can determine if two values are equal or not. Object.is() helper function is introduced in ES6.

Syntax

Object.is(val1, val2)

Parameters

Values to compare val1 and val2.

Return Value

Object.is() returns a Boolean which indicates if val1 is having the same value as val2 or not.

Value Comparision

val1 and val2 are same in case of Object.is() in case of following conditions:

val1 and val2 are both null

1
2
3
4
let val1 = null;
let val2 = null;
Object.is(val1, val2)
// true

val1 and val2 are both undefined.

1
2
3
4
let val1 = undefined;
let val2 = undefined;
Object.is(val1, val2)
// true

val1 and val2 are both NaN

1
2
3
4
let val1 = NaN;
let val2 = NaN;
Object.is(val1, val2)
// true

val1 and val2 are both of the same Boolean value i.e. true or false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let val1 = true;
let val2 = true;
Object.is(val1, val2)
// true

let val3 = false;
let val4 = false;
Object.is(val3, val4)
// true

let val5 = true;
let val6 = false;
Object.is(val5, val6)
// false

val1 and val2 are referencing the same object.

1
2
3
4
5
6
7
8
9
let val1 = { name: "Object comparison" };
let val2 = val1;
Object.is(val1, val2)
// true

let val3 = { name: "Object comparison" };
let val4 = { name: "Object comparison" };
Object.is(val3, val4)
// false

val1 and val2 are both non-zero numbers and have the same value.

1
2
3
4
let val1 = 42;
let val2 = 42;
Object.is(val1, val2)
// true

val1 and val2 are both either +0 or -0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let val1 = +0;
let val2 = +0;
Object.is(val1, val2)
// true

let val3 = -0;
let val4 = -0;
Object.is(val3, val4)
// true

let val5 = +0;
let val6 = -0;
Object.is(val5, val6)
// false

Note on Object.is(), "==" and "==="

  • Object.is() works differently than "==" operator as it does not apply coercions before comparing the values.
1
2
3
4
5
6
7
8
9
console.log(1 == [1]);
// true
console.log(1 == "1");
// true

console.log(Object.is(1, [1]));
// false
console.log(Object.is(1, "1"));
// false
  • Object.is() also works differently than "===" operator as the "===" operator treats +0 and -0 as equals and NaN as not equal to itself.
1
2
3
4
5
6
7
8
9
console.log(+0 === -0);
// true
console.log(Object.is(+0, -0));
// false

console.log(NaN === NaN);
// false
console.log(Object.is(NaN, NaN));
// true

Cover Image: Image by Martin Pyško from Pixabay


Share and support us

Share on social media and help us reach more people