Why Object.is ?
Object.is () checks whether the two values are of the same value. The two values are the same when one of the following is true:
- when they both have the same object
- both when and when
- when both are +0
- when both are -0
- both right and wrong
- two characters of the same length, when they are the same character in the same order
- when they are both NaN
- when both are undefined
- when both are empty
- or both are non-zero and not both NaN and both have the same value.
- This is not the same as the == operator. == The operator applies the same difficulty to both sides before testing the equation (if not the same type) (but “==”), but Object.is does not force both values.
This is not the same as being equal to === operator. The operator === (and == operator) accepts -0 and +0 are equal and treats Number.NaN as not equal to NaN.
Syntax:
Object.is(arr1, arr2);
- arr1: The first value to compare.
- arr2: The second value to compare.
| arr1 | arr2 | == | === | Object.is |
| undefined | undefined | true | true | true |
| null | null | true | true | true |
| true | true | true | true | true |
| false | false | true | true | true |
| “foo” | “foo” | true | true | true |
| { foo: “bar” } | x | true | true | true |
| 0 | 0 | true | true | true |
| +0 | -0 | true | true | false |
| 0 | false | true | false | false |
| “” | 0 | true | false | false |
| “0” | 0 | true | false | false |
| “17” | 17 | true | false | false |
| [1,2] | “1,2” | true | false | false |
| new String(“foo”) | “foo” | true | false | false |
| null | undefined | true | false | false |
| null | false | false | false | false |
| undefined | false | false | false | false |
| new String(“foo”) | new String(“foo”) | false | false | false |
| 0 | null | false | false | false |
| 0 | NaN | false | false | false |
| “foo” | NaN | false | false | false |
| NaN | NaN | false | false | true |
| { foo: “bar” } | { foo: “bar” } | false | false | false |
JavaScript Object.is Example
var test = { a: 1 };
console.log( Object.is(test, test) )
console.log( Object.is(null, null) )
console.log( Object.is(0, -0) )
console.log( Object.is(-0, -0) )
console.log(Object.is(NaN, 0 / 0))
Object.is('foo', 'foo');
console.log(Object.is(window, window));
Object.is('foo', 'bar');
console.log(Object.is([], []));
output:
true
true
false
true
true
true
false
Polyfill
if (!Object.is) {
Object.is = function(x, y) {
// SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
};
}
Browser Support
| Chrome | 30 |
| Edge | yes |
| Firefox | 22 |
| Internet Explorer | no |
| Opera | yes |
| Safari | 9 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 22 |
| Opera Android | yes |
Leave a comment