DEV Community

Cover image for Comparing values using Object.is() in Javascript
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Comparing values using Object.is() in Javascript

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

let val1 = null;
let val2 = null;
Object.is(val1, val2)
// true
Enter fullscreen mode Exit fullscreen mode

val1 and val2 are both undefined.

let val1 = undefined;
let val2 = undefined;
Object.is(val1, val2)
// true
Enter fullscreen mode Exit fullscreen mode

val1 and val2 are both NaN

let val1 = NaN;
let val2 = NaN;
Object.is(val1, val2)
// true
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

val1 and val2 are referencing the same object.

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

Enter fullscreen mode Exit fullscreen mode

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

let val1 = 42;
let val2 = 42;
Object.is(val1, val2)
// true

Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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

  • Object.is() works differently than "==" operator as it does not apply coercions before comparing the values.
console.log(1 == [1]);
// true
console.log(1 == "1");
// true

console.log(Object.is(1, [1]));
// false
console.log(Object.is(1, "1"));
// false
Enter fullscreen mode Exit fullscreen mode
  • Object.is() also works differently than "===" operator as the "===" operator treats +0 and -0 as equals and NaN as not equal to itself.
console.log(+0 === -0);
// true
console.log(Object.is(+0, -0));
// false

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

Enter fullscreen mode Exit fullscreen mode

Cover Image: Image by Martin Pyško from Pixabay


This article was first published on hackinbits.com

Top comments (0)