-1

Can somebody explain this weird behavior of javascript on comparing the existence of an object in an array

Yogesh Aggarwal
  • 1,071
  • 2
  • 12
  • 30
  • 5
    `includes` checks equality, and objects are only equal if they point to the same exact object in memory. each `{n:1}` in your sample is a different literal creating a different object, if you stored them you could modify them independently of each other – Klaycon Mar 05 '20 at 18:00
  • 1
    you could use JSON.stringify to compare them (aka. convert them to strings and compare the strings) – Teiem Mar 05 '20 at 18:03

1 Answers1

1

Equality checks work different for objects than for strings or numbers:

console.log('hello' === 'hello');
console.log(2 === 2);
console.log({x:2} === {x:2});
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • Your answer is a rewording of the question, nothing more. – connexo Mar 05 '20 at 18:03
  • 3
    @connexo it only rewords the question if that's knowledge OP already has. If it isn't, then it's definitely an explanation for why the behaviour observed is what it is. Since we can't really determine what OP knows or not, we can at least conclude that the question is *not* "why does the equality used by `includes` work the same way as the equality operator" to which, indeed, the answer "the equality works like so" is a rewording. – VLAZ Mar 05 '20 at 18:04
  • 1
    *Equality checks work different for objects than for strings or numbers* - that is exactly the observation that OP made themselves, and caused them to ask a question. Your answer holds **no** additional information. – connexo Mar 05 '20 at 18:09