0

Does includes method consider references too.

Eg:

let temp1 = [{a:5,b:3},{a:10,b:10}]
temp1.includes(temp1[0]) 
//returns true

let obj = {...temp1[0]}
temp1.includes(obj)
//returns false

Can someone please explain how includes method is working in this context

3
  • 3
    They must be the exact same object. obj === temp1[0] // false Commented Jul 23, 2020 at 13:30
  • I understand they are not the same object but how is includes method working when passing object having multiple key-value pairs. Commented Jul 23, 2020 at 13:37
  • In the first example, you are asking if temp1 contains an object, this object comes from temp1 so it's true. It's not comparing values or keys. Commented Jul 23, 2020 at 13:39

1 Answer 1

2

When you use temp1[0] you are comparing it with the exact same object, which is its first item, so it will return true.

When you uses the spread operator (...temp1) you are cloning the object, so when you compare both objects they won't be the exact same objects, and it will return false.

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

2 Comments

includes compares values in an array, so if we pass objects which has keys does it compare key-value pairs. I wanted to know how includes work when objects are passed.
@bhasuru, no, it doesn't compare key-values, it compares between the address of the object in memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.