-1

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

2
  • 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 Commented Mar 5, 2020 at 18:00
  • 1
    you could use JSON.stringify to compare them (aka. convert them to strings and compare the strings) Commented Mar 5, 2020 at 18:03

1 Answer 1

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});

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is a rewording of the question, nothing more.
@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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.