Object.is

Did you know that you can read content offline by using one of these tools? If you would like to read offline MDN content in another format, let us know by commenting on Bug 665750.

Dash App

This is an experimental technology, part of the Harmony (EcmaScript 6) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

This content covers features introduced in Firefox 22

Summary

Determines whether two values are the same value.

Method of Object
Implemented in JavaScript 1.8.5+
ECMAScript Edition ECMAScript 6th Edition

Syntax

var isSame = Object.is(value1, value2);

Parameters

value1
The first value to compare.
value2
The second value to compare.

Description

Object.is() determines whether two values are the same value.  Two values are the same if one of the following holds:

  • both undefined
  • both null
  • both true or both false
  • both strings of the same length with the same characters
  • both the same object
  • both numbers and
    • both +0
    • both -0
    • both NaN
    • or both non-zero and both not NaN and both have the same value

This is not the same as being equal according to the == operator.  The == operator applies various coercions to both sides before testing for equality (resulting in such behavior as "" == false being true), but Object.is doesn't coerce either value.

This is also not the same as being equal according to the === operator.  The === operator (and the == operator as well) treats the number values -0 and +0 as equal, and it treats NaN as not equal to NaN.

Compatibility

Object.is is a proposed addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use Object.is when there is still no native support.

if (!Object.is) {
  Object.is = function(v1, v2) {
    if (v1 === 0 && v2 === 0)
      return 1 / v1 === 1 / v2;
    if (v1 !== v1)
      return v2 !== v2;
    return v1 === v2;
  };
}

Examples

Object.is("foo", "foo");     // true
Object.is(window, window);   // true

Object.is("foo", "bar");     // false
Object.is([], []);           // false

var test = {a: 1};
Object.is(test, test)       // true

Object.is(null, null)       // true

// Special Cases
Object.is(0, -0);            // false
Object.is(-0, -0);           // true
Object.is(NaN, 0/0);         // true

 

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 22.0 (22) Not supported Not supported Not supported
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Not supported 22.0 (22) Not supported Not supported Not supported

 

Tags (4)