2
<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert([[25,4]].includes([25,4]));
  </script>

  <p>...After the script.</p>

</body>

</html>

When I run the above code, it outputs "false", which isn't correct. If I change [[25,4]].includes([25,4]) to ['a'].includes('a'), it outputs the correct answer "true". Why does it do that?

2
  • 1
    includes tests for strict equality meaning the two arrays would need to be the same array not two arrays that happen to hold the same values. It doesn't work for the same reason [[25,5]] === [[25,5]] is false. Commented Sep 25, 2018 at 0:07
  • var tuple = [25, 24]; alert([tuple].includes(tuple)) there you go Commented Sep 25, 2018 at 0:12

1 Answer 1

2

That's because [25,4] !== [25,4] as the two operands refer to 2 different array objects. JavaScript do no consider 2 different objects equal. ['a'].includes('a') returns true as 'a' is a string (primitive value.) If you convert the 'a' into a String object the .includes method should return false. (Check What is the difference between JavaScript object and primitive types?)

'a' === 'a' // true
new String('a') === new String('a') // false
[new String('a')].includes(new String('a')) // false

The .includes method should return true if you change your code into:

const item = [25,4];
const array = [item];
console.log(array.includes(item)); // true
Sign up to request clarification or add additional context in comments.

4 Comments

But I have an array of lots of smaller arrays. So, what should I do to tell if a smaller array is this large array of arrays if I can't assign names to them one by one?
@ZhiweiLiu Check this question: javascript search array of arrays
And I've found a duplicate question: stackoverflow.com/questions/19543514/…
What is the way to check that a String object say a:string with value abc contains a?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.