0

The Object.is() method determines whether two values are the same value.

Return value: A Boolean indicating whether or not the two arguments are the same value.

I can test Object.is() with simple types like:

Object.is('hello', 'hello'); // true
Object.is(1, 1); // true
Object.is(null, null); // true

I saw also on MDN that I can use it with "window" object like that:

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

When I tried to compare 2 simple "exact" values it seems not working (or maybe I'm using it in the wrong way)

Having those 2 simple objects:

var o1 = {a: "a"};
var o2 = {a: "a"};

All those comparisons returns false!

Object.is(o1, o2); // false
Object.is(o1, {a: "a"}); // false
Object.is({a: "a"}, {a: "a"}); // false

Can you help by explaining why the result is false or how I'm using Object.is() in a wrong way?

Community
  • 1
  • 1
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65
  • 2
    because they are not the same object. `var o1 = {a: "a"}; var o2 = o1; Object.is(o1, o2);` – epascarello Feb 23 '17 at 14:10
  • See this table on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#A_model_for_understanding_equality_comparisons) – barbsan Feb 23 '17 at 14:12

3 Answers3

2

It's because they aren't the same reference.

Notice:

var o1 = {a: "a"};
var o2 = o2;
Object.is(o1, o2);

results in true.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

The reason it's that when we have an object we store the reference not the value itself. If you compare window with window they point to the same object reference.

You can use https://lodash.com/docs/4.17.4#isEqual to compare object values.

williamcabrera4
  • 270
  • 2
  • 12
0

Two different objects are never the "exact same". Object equality is based on identity, not contents. If you have some semantics in your application about objects representing conceptually the same information, you can write your own comparison code to make that determination.

In your code, every { } object initializer creates a distinct object.

Pointy
  • 405,095
  • 59
  • 585
  • 614