JavaScript ES6 Object Extensions - Object.is()
----------------------------------------------
In this topic, we will cover the javascript ES6 Object extensions method which is Object.is()
JavaScript Object.is()
The Object.is()
a static method is used to determine if two values are the same.
Syntax
Object.is(value1, value2)
Here value1 and value2 are the first value to compare with the second value.
It returns boolean
Examples
console.log(Object.is('123', 123));
// Expected output: false
console.log(Object.is(NaN, NaN));
// Expected output: true
console.log(Object.is(-0, 0));
// Expected output: false
const objOne = {};
console.log(Object.is(objOne, {}));
// Expected output: false
A most important point to note is that the Object.is()
is not equivalent to the ==
operator but it behave like ===
But with the main two difference
- -0 and +0
- NaN
As we know the ===
operator treats -0
and +0
are the same value but this is not the case. In Object.is()
treats +0 and -0 as different value
const valueOne = +0,
const valueTwo = -0;
console.log(valueOne === valueTwo );
//return will be true
//But if we use Object.is()
console.log(Object.is(valueOne,valueTwo) );
//return will be false
Object.is()
treats NaN and NaN as same value
let numCheck = NaN;
console.log(Object.is(numCheck ,numCheck ));
//return will be true
Now lets check few examples
// Case 1: Evaluation result is the same as using ===
Object.is(55, 55); // true
Object.is("coderuck", "coderuck"); // true
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { name: 'coderuck };
const bar = { name: 'coderuck };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true
// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true
Categories: Java Script Tags: #ES6, #JavaScript,