Schovi
Schovi

Reputation: 1990

How does Immutable.js comparation work?

I have been using Immutable.js for some time, and just now I found out that the comparison operator does not work how I thought.

My code is simple:

a = Immutable.Map({a:1, b:[1,2,3]})
b = Immutable.Map({a:1, b:[1,2,3]})
a == b // false
Immutable.is(a, b) // false

Is there any way to compare two of the same Immutable objects and get true?

Functional logic tells me they should be equal, but in JavaScript they are not.

Upvotes: 2

Views: 749

Answers (2)

Jeremy Larter
Jeremy Larter

Reputation: 558

(function () {
  var c = [1,2,3],
      a = Immutable.Map({a:1, b: c}),
      b = Immutable.Map({a:1, b:[1,2,3]});
  c[0] = 9;

  console.log(JSON.stringify(a), JSON.stringify(b));
}());

The way you are creating a and b would allow you to have side effects if you retained a reference (such as c) to the inner array as demonstrated above.

I think the comparisons are correctly telling you that the objects are not the same.

Upvotes: 0

c-smile
c-smile

Reputation: 27460

a == b essentially compares "addresses" of two objects. And in your code you create two distinct instances of objects and so they are always different, therefore a == b is false by JavaScript specification.

As of how to compare two objects in JS, check this: Object comparison in JavaScript

Upvotes: 3

Related Questions